package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.help.StageAverageStayTimeHelp;
import com.xbongbong.crm.service.SearchCustomerService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OtherExpenseSheetTypeEnum;
import com.xbongbong.paas.enums.OtherIncomeSheetTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.EsignHelp;
import com.xbongbong.paas.help.SharePermissionHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasCommentModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.PaasProcessDataModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.pojo.ButtonExtraPojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetaPhonePojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.UserFormPermissionVO;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.DetailTabConfigService;
import com.xbongbong.paas.service.EsignService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.RoleSimpleVO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.data.FormDataEsService;
import com.xbongbong.parent.help.CommonPermissionHelp;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.detailtab.pojo.BomVersionPojo;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.domain.entity.PersonLabelEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.enums.AmountFlagEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.ReceiveStatusEnum;
import com.xbongbong.pro.enums.RefundStatusEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.errorcodes.CommuicatePlanErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.enums.permission.enums.DeleteProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.permission.enums.UpdateProPermissionAliasEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormOwnerUniqueEnum;
import com.xbongbong.pro.esign.pojo.dto.EsignFlowStatusDTO;
import com.xbongbong.pro.esign.pojo.vo.EsignFlowStatusVO;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.form.pojo.dto.ChildProductDTO;
import com.xbongbong.pro.form.pojo.dto.FormConfigGetDTO;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.label.pojo.dto.PersonLabelFindDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.statistic.enums.ChartCategoryAliasEnum;
import com.xbongbong.pro.webdetail.pojo.SealPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.TabConstant;
import com.xbongbong.saas.domain.entity.CommunicatePlanUserEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.CustomerFocusEntity;
import com.xbongbong.saas.domain.entity.InvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.OpportunityFocusEntity;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.PaymentBalanceEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.PublicGroupSeniorEntity;
import com.xbongbong.saas.domain.entity.PurchaseInvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.SaleStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowNodeEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.enums.BusinessCommentEnum;
import com.xbongbong.saas.enums.BusinessDetailButtonEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CreditLimitStatusEnum;
import com.xbongbong.saas.enums.CreditTemporaryApplyStatusEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticDistributorEnum;
import com.xbongbong.saas.enums.CustomerStatementStatisticEnum;
import com.xbongbong.saas.enums.CustomerStatementStatusEnum;
import com.xbongbong.saas.enums.DetailTabEnum;
import com.xbongbong.saas.enums.EsignFlowStatusEnum;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OrderOutStockExpressStatusEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.RowNameEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.WorkOrderFlowNodeTypeEnum;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.WorkOrderStageRobTypeEnum;
import com.xbongbong.saas.enums.WorkOrderStageRuleEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.WorkOrderTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.CommunicateBaseEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CreditTemporaryLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorContactEnum;
import com.xbongbong.saas.enums.business.ExpenseEnum;
import com.xbongbong.saas.enums.business.ExpressCodeEnum;
import com.xbongbong.saas.enums.business.FundTransferEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OrderOutStockEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.PaymentTaskEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.BomStatusEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.CommunicatePlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.CustomerTypeEnum;
import com.xbongbong.saas.enums.dictionary.OrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentTaskStatusEnum;
import com.xbongbong.saas.enums.dictionary.ProductionOrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.ReturnStatusEnum;
import com.xbongbong.saas.enums.dictionary.ReturnedStatusEnum;
import com.xbongbong.saas.enums.dictionary.ShipStatusEnum;
import com.xbongbong.saas.enums.dictionary.TransferNewStatusEnum;
import com.xbongbong.saas.enums.dictionary.WorkOrderShipStatusEnum;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerStageLogModel;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.InvoiceRelationshipModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.LikeModel;
import com.xbongbong.saas.model.OpportunityFocusModel;
import com.xbongbong.saas.model.OpportunityStageLogModel;
import com.xbongbong.saas.model.PayBalanceModel;
import com.xbongbong.saas.model.PaymentBalanceModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.PublicGroupSeniorModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseInvoiceRelationshipModel;
import com.xbongbong.saas.model.SaleStageModel;
import com.xbongbong.saas.model.ScoreRangeModel;
import com.xbongbong.saas.model.StockFlowBillModel;
import com.xbongbong.saas.model.WorkOrderCcModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderStageModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.ContractPerformanceService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.service.MobileDetailService;
import com.xbongbong.saas.service.PersonLabelService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.ProductionOrderService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WorkOrderFormService;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.FundSetHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.enums.RoleEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.ContractCompareUtil;
import com.xbongbong.util.NameUtil;
import com.xbongbong.workflow.model.impl.WorkflowModelImpl;
import com.xbongbong.workorder.service.WorkOrderBasicService;
import com.xbongbong.workorder.service.WorkOrderFlowUserService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/7/12 14:51
 * @since v1.0
 */
@Component
public class ProDetailHandlerHelp {

    public static final Logger LOG = LoggerFactory.getLogger(ProDetailHandlerHelp.class);

    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasProcessDataModel paasProcessDataModel;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private ContractPerformanceService contractPerformanceService;
    @Resource
    private EsHelper esHelper;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private OpportunityFocusModel opportunityFocusModel;
    @Resource
    private MobileDetailService mobileDetailService;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private OpportunityStageLogModel opportunityStageLogModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private WorkOrderStageModel workOrderStageModel;
    @Resource
    private ProductService productService;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerStageLogModel customerStageLogModel;
    @Resource
    private ProductionOrderService productionOrderService;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private WorkOrderFormService workOrderFormService;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private WorkOrderBasicService workOrderBasicService;
    @Resource
    private WorkOrderCcModel workOrderCcModel;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private WorkOrderFlowUserService workOrderFlowUserService;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private SharePermissionHelp sharePermissionHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaymentBalanceModel paymentBalanceModel;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private SearchCustomerService searchCustomerService;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PayBalanceModel payBalanceModel;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private FundSetHelp fundSetHelp;
    @Resource
    private InvoiceRelationshipModel invoiceRelationshipModel;
    @Resource
    private PurchaseInvoiceRelationshipModel purchaseInvoiceRelationshipModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private InvoiceCommonHelper invoiceCommonHelper;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private PaasCommentModel paasCommentModel;
    @Resource
    private LikeModel likeModel;
    @Resource
    private EsignService esignService;
    @Resource
    private EsignHelp esignHelp;
    @Resource
    private UserService userService;
    @Resource
    private LabelModel labelModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private MarketManagementBusinessHelp marketManagementBusinessHelp;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private ScoreRangeModel scoreRangeModel;
    @Resource
    private DetailTabConfigService detailTabConfigService;
    @Resource
    private SaasPaymentSheetHelper saasPaymentSheetHelper;
    @Resource
    private WorkflowModelImpl workflowModel;
    @Resource
    private SaasPaySheetHelper saasPaySheetHelper;
    @Resource
    private PersonLabelService personLabelService;
    @Resource
    private SaasOtherIncomeHelp saasOtherIncomeHelp;
    @Resource
    private SaasOtherExpenseHelp saasOtherExpenseHelp;
    @Resource
    private SaleStageModel saleStageModel;
    @Resource
    private StageAverageStayTimeHelp stageAverageStayTimeHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private FormDataEsService formDataEsService;
    @Resource
    private StockFlowBillModel stockFlowBillModel;
    @Resource
    private PublicGroupSeniorModel publicGroupSeniorModel;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private ContractCompareUtil contractCompareUtil;
    @Resource
    private CommonPermissionHelp commonPermissionHelp;

    /**
     * 处理详情页特殊返回，bom版本，跨月
     *
     * @param dataDetailPojo
     * @param paasFormDataEntityExt
     * @param businessType
     * @throws XbbException
     */
    public void handleDetailSpecialParam(DataDetailPojo dataDetailPojo, PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType, UserVO userVO) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        JSONObject data = paasFormDataEntityExt.getData();
        switch (redundantTemplateTypeEnum) {
            case BOMBILL:
                if (userVO.getPermSet().contains(ProPermissionAliasEnum.BOM_BILL_UPDATE.getAlias())) {
                    Integer isDefault = getIntegerOrDefaultFromFormData(data, BomBillEnum.VERSION_LINK_TEXT.getAttr(), BasicConstant.ZERO);
                    BomVersionPojo bomVersionPojo = new BomVersionPojo();
                    bomVersionPojo.setIsDefault(Objects.equals(isDefault, BasicConstant.IS_DEFAULT));
                    bomVersionPojo.setIsShow(true);
                    dataDetailPojo.setBomVersionPojo(bomVersionPojo);
                }
                break;
            case INVOICE:
                Long invoiceDate = FastJsonHelper.getLongOrDefaultFromFormData(data, InvoiceEnum.INVOICE_DATE.getAttr(), 0L);
                if (DateTimeUtil.getMonthNum(invoiceDate, DateTimeUtil.getInt()) >= 1) {
                    dataDetailPojo.setCrossMonth(true);
                }
                break;
            case PURCHASE_INVOICE:
                Long purchaseInvoiceDate = FastJsonHelper.getLongOrDefaultFromFormData(data,PurchaseInvoiceEnum.INVOICE_DATE.getAttr(), 0L);
                if (DateTimeUtil.getMonthNum(purchaseInvoiceDate, DateTimeUtil.getInt()) >= 1) {
                    dataDetailPojo.setCrossMonth(true);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 处理详情页头部标题名称
     *
     * @param titlePojo
     * @param paasFormDataEntityExt
     * @param businessType
     * @throws XbbException
     */
    public void handleDetailRowName(DetailTitlePojo titlePojo, PaasFormDataEntityExt paasFormDataEntityExt, Integer businessType) throws XbbException {
        RowNameEnum rowNameEnum = RowNameEnum.getByBusinessType(businessType);
        String corpid = paasFormDataEntityExt.getCorpid();
        String name = "";
        if (rowNameEnum != null) {
            if (Objects.equals(rowNameEnum.getAttr(), FieldTypeEnum.SERIALNO.getAlias())) {
                name = paasFormDataEntityExt.getSerialNo();
            } else {
                name = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), rowNameEnum.getAttr(), "");
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<String, Object> dataParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.CORPID, corpid);
            param.put(TabConstant.SAAS_MARK, SaasMarkEnum.SAAS.getCode());
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.FLOW_STATUS_IN, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            switch (xbbRefTypeEnum) {
                case INVENTORY:
                    param.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.INSTOCK.getCode());
                    dataParam.put(InstockEnum.REF_ID.getAttr(), paasFormDataEntityExt.getId());
                    dataParam.put(InstockEnum.TYPE.getAttr(), InstockTypeEnum.INVENTORY_INSTOCK.getCode());
                    Integer instockCount = paasProcessDataModel.getCountByCondition(dataParam, param);
                    if (Objects.nonNull(instockCount) && instockCount > 0) {
                        name += I18nMessageUtil.getMessage(BusinessConstant.INSTOCK_APPROVAL);
                    }
                    param.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.OUTSTOCK.getCode());
                    dataParam.put(InstockEnum.TYPE.getAttr(), OutstockTypeEnum.INVENTORY_OUTSTOCK.getCode());
                    Integer outstockCount = paasProcessDataModel.getCountByCondition(dataParam, param);
                    if (Objects.nonNull(outstockCount) && outstockCount > 0) {
                        name += I18nMessageUtil.getMessage(BusinessConstant.OUTSTOCK_APPROVAL);
                    }
                    break;
                case TRANSFER:
                    param.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.INSTOCK.getCode());
                    dataParam.put(InstockEnum.REF_ID.getAttr(), paasFormDataEntityExt.getId());
                    dataParam.put(InstockEnum.TYPE.getAttr(), InstockTypeEnum.TRANSFER_INSTOCK.getCode());
                    instockCount = paasProcessDataModel.getCountByCondition(dataParam, param);
                    if (Objects.nonNull(instockCount) && instockCount > 0) {
                        name += I18nMessageUtil.getMessage(BusinessConstant.INSTOCK_APPROVAL);
                    }
                    param.put(StringConstant.BUSINESS_TYPE, XbbRefTypeEnum.OUTSTOCK.getCode());
                    dataParam.put(InstockEnum.TYPE.getAttr(), OutstockTypeEnum.TRANSFER_OUTSTOCK.getCode());
                    outstockCount = paasProcessDataModel.getCountByCondition(dataParam, param);
                    if (Objects.nonNull(outstockCount) && outstockCount > 0) {
                        name += I18nMessageUtil.getMessage(BusinessConstant.OUTSTOCK_APPROVAL);
                    }
                    break;
                default:
                    break;
            }
        }
        titlePojo.setName(name);
    }

    /**
     * 处理详情页印章
     *
     * @param businessType          业务类型
     * @param titlePojo             标题
     * @param paasFormDataEntityExt 数据
     * @throws XbbException 异常
     */
    public void handelDetailSeal(Integer businessType, DetailTitlePojo titlePojo, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        JSONObject dataList = paasFormDataEntityExt.getData();
        switch (xbbRefTypeEnum) {
            case PAYMENT:
                List<SealPojo> sealPojoList = new ArrayList<>();
                String paymentStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getCode());
                if (Objects.equals(paymentStatus, PaymentStatusEnum.BAD_DEBT.getCode())) {
                    sealPojoList.add(new SealPojo(PaymentStatusEnum.BAD_DEBT.getName()));
                }
                if (Objects.equals(paymentStatus, PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode())) {
                    sealPojoList.add(new SealPojo(PaymentStatusEnum.PARTIAL_BAD_DEBT.getName()));
                }
                Integer paymentRed = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, PaymentEnum.RECEIVABLE_IS_RED.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(paymentRed, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case PAY_PLAN:
                sealPojoList = new ArrayList<>();
                String payPlanStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());
                if (Objects.equals(payPlanStatus, PayPlanStatusEnum.BAD_DEBT.getCode())) {
                    sealPojoList.add(new SealPojo(PayPlanStatusEnum.BAD_DEBT.getName()));
                }
                if (Objects.equals(payPlanStatus, PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode())) {
                    sealPojoList.add(new SealPojo(PayPlanStatusEnum.PARTIAL_BAD_DEBT.getName()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case INVOICE:
                sealPojoList = new ArrayList<>();
                Integer isCancel = getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.IS_CANCEL.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(isCancel, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.CANCEL.getAttr()));
                }
                Integer isRed = getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.IS_RED.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(isRed, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case PURCHASE_INVOICE:
                sealPojoList = new ArrayList<>();
                Integer purchaseInvoiceisCancel = getIntegerOrDefaultFromFormData(dataList,PurchaseInvoiceEnum.IS_CANCEL.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(purchaseInvoiceisCancel, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.CANCEL.getAttr()));
                }
                Integer purchaseInvoiceIsRed = getIntegerOrDefaultFromFormData(dataList,PurchaseInvoiceEnum.IS_RED.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(purchaseInvoiceIsRed, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case QUOTATION:
                sealPojoList = new ArrayList<>();
                Integer archived = getIntegerOrDefaultFromFormData(dataList, QuotationEnum.ARCHIVED.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(archived, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.ARCHIVED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                sealPojoList = new ArrayList<>();
                Integer archivedStatement = dataList.getIntValue(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr());
                if (Objects.equals(archivedStatement, BasicConstant.ONE)) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.ARCHIVED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case PAYMENT_SHEET:
                sealPojoList = new ArrayList<>();
                //回款单类型
                String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.WRITE_OFF.getCode());
                boolean isBadFlag = PaymentSheetTypeEnum.isBad(paymentSheetType);
                if (isBadFlag) {
                    sealPojoList.add(new SealPojo(PaymentStatusEnum.BAD_DEBT.getName()));
                }
                boolean isRedFlag = PaymentSheetTypeEnum.isRed(paymentSheetType);
                if (isRedFlag) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case PAY_SHEET:
                sealPojoList = new ArrayList<>();
                //付款单类型
                String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                isBadFlag = PaySheetTypeEnum.isBad(paySheetType);
                if (isBadFlag) {
                    sealPojoList.add(new SealPojo(PayPlanStatusEnum.BAD_DEBT.getName()));
                }
                isRedFlag = PaySheetTypeEnum.isRed(paySheetType);
                if (isRedFlag) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case OTHER_INCOME:
                sealPojoList = new ArrayList<>();
                //其他收入单类型
                String otherIncomeSheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr(), OtherIncomeSheetTypeEnum.OTHER_INCOME.getCode());
                isRedFlag = OtherIncomeSheetTypeEnum.isRed(otherIncomeSheetType);
                if (isRedFlag) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            case OTHER_EXPENSE:
                sealPojoList = new ArrayList<>();
                //其他支出单类型
                String otherExpenseSheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr(), OtherExpenseSheetTypeEnum.OTHER_EXPENSE.getCode());
                isRedFlag = OtherExpenseSheetTypeEnum.isRed(otherExpenseSheetType);
                if (isRedFlag) {
                    sealPojoList.add(new SealPojo(SaasButtonEnum.RED.getAttr()));
                }
                titlePojo.setSealPoJoList(sealPojoList);
                break;
            default:
                break;
        }
    }

    /**
     * 处理详情页tab
     *
     * @param handelDetailPojo
     * @param platFormEnum
     * @param explainMap            attr-explain实体的map
     * @param feeType 套餐类型
     * @throws XbbException
     */
    public void handelDetailTab(HandelDetailPojo handelDetailPojo, PlatFormEnum platFormEnum, Map<String, FieldAttrEntity> explainMap, Integer feeType) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = handelDetailPojo.getPaasFormDataEntityExt();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer distributorMark = handelDetailPojo.getDistributorMark();
        List<DetailTabPojo> tabPojoList = handelDetailPojo.getTabPojoList();
        String corpid = paasFormDataEntityExt.getCorpid();
        String userId = userVO.getUserId();
        List<BusinessDetailTabEnum> tabEnumList;
        // 判断当前公司有没有开启呼叫中心
        boolean isActiveCall;
        boolean isActiveAliyunCall = callCenterCommonService.isActiveAliyunCall(corpid, userId).IsActiveAliyunAndHasRole();
        if (Objects.equals(platFormEnum, PlatFormEnum.WEB)) {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
            isActiveCall = callCenterCommonService.isOpenCallAndAgent(corpid, userId);
        } else {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, userVO.getPermSet());
            isActiveCall = callCenterCommonService.isOpenCallDingTalk(corpid, userId);
        }
        isActiveCall = isActiveCall||isActiveAliyunCall;    // 兼容原呼叫中心  开通了其中一个就显示 通话记录tab
        // 判断应用是否启用
        boolean isSmsUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.GROUP_MESSAGE.getAlias(), Integer.valueOf(1), corpid);
        // 判断当前员工有没有短信权限
        boolean canSms = isSmsUse && userVO.getPermSet().contains(ProPermissionAliasEnum.SMS_VIEW.getAlias()) ? true : false;

        //判断有没有开启工作流
        boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);
        if(!isOpenWorkflow){
            tabEnumList = tabEnumList.stream().filter(v -> !Objects.equals(v.getAnEnum(), DetailTabEnum.APPROVAL_RECORDS)).collect(Collectors.toList());
        }
        // 旗舰版
        boolean ultimateType = Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType);
        List<String> paasAlias = new ArrayList<>();
        tabEnumList.forEach(item ->{
            if (item.getFormBusinessType() != 0){
                paasAlias.add(XbbRefTypeEnum.getByCode(item.getFormBusinessType()).getAlias());
            }
        });
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", paasFormDataEntityExt.getCorpid());
        param.put("aliasIn", paasAlias);
        param.put("del", DelEnum.NORMAL.getDel());
        boolean isDistributor = XbbRefTypeEnum.isDistributorBusinessType(businessType);
        // 经销商拆分菜单的需要经销商的菜单tab（经销商联系人等） + 非经销商的菜单tab（回款等），产品需要两种菜单（合同 + 订货单）
        if (!isDistributor && !Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
            param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        }
        List<PaasMenuEntity> paasMenuEntitys = paasMenuModel.findEntitys(param);
        // 记录businessType与menuName的关系
        HashMap<Integer, String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Integer, PaasMenuEntity> menuMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 拆分菜单的走这里
        if (isDistributor) {
            paasMenuEntitys.forEach(item -> {
                int code = XbbRefTypeEnum.getByAlias(item.getAlias()).getCode();
                if (!menuMap.containsKey(code) || Objects.equals(item.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    menuMap.put(code, item);
                }
            });
            menuMap.forEach((key, value) -> paasBusinessTypeToName.put(key, value.getName()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
            // 像产品那样的tab走这里
            paasMenuEntitys.forEach(item -> {
                int code = XbbRefTypeEnum.getByAlias(item.getAlias()).getCode();
                if (menuMap.containsKey(code)) {
                    PaasMenuEntity paasMenuEntity = menuMap.get(code);
                    paasMenuEntity.setName(paasMenuEntity.getName() + StringConstant.VERTICAL_LINE + item.getName());
                } else {
                    menuMap.put(code, item);
                }
            });
            menuMap.forEach((key, value) -> paasBusinessTypeToName.put(key, value.getName()));
        } else {
            // 只需要非经销商的tab菜单的走这里
            paasMenuEntitys.forEach(item -> paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName()));
        }
        //协同团队
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,businessType,false,mainUserMap,coUserMap);

        // 当前数据的创建人、负责人、协同人、当前操作人
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(userVO);
        handlerExplainDTO.setUserId(userId);
        handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));
        handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);

        Long modelType = fundSetService.getModelType(corpid, XbbRefTypeEnum.CRM);
        switch (redundantTemplateTypeEnum) {
            case CONTRACT:
                boolean openDistribution = contractPerformanceService.openDistribution(corpid);
                // 判断关联产品字段是否可见
                boolean contractProduct = commonHelp.attrCanSee(ContractEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (!openDistribution && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_PERFORMANCE)) {
                        continue;
                    }
                   /* if (!contractProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_PRODUCT_LIST)) {
                        continue;
                    }*/
                    Integer hasRed = getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), ContractEnum.HAS_RED.getAttr(), BasicConstant.ZERO);
                    if (!Objects.equals(hasRed, BasicConstant.ONE) && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_REFUND)) {
                        continue;
                    }
                    if ( !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) && !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_PAYMENT) ) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    //判断是否有回款单，是否有应收款、回款计划权限
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_PAYMENT) ) {
                        Boolean isHasPayment = false;
                        Boolean isHasPaymentSheet = false;
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) ) {
                            isHasPaymentSheet = true;
                        }
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) ) {
                            isHasPayment = true;
                        }
                        detailTabPojo.setIsHasPayment(isHasPayment);
                        detailTabPojo.setIsHasPaymentSheet(isHasPaymentSheet);
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case REFUND:
                openDistribution = contractPerformanceService.openDistribution(corpid);
                // 判断关联产品字段是否可见
                //boolean refundProduct = commonHelp.attrCanSee(RefundEnum.PRODUCTS.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (!openDistribution && Objects.equals(tabEnum, BusinessDetailTabEnum.REFUND_PERFORMANCE)) {
                        continue;
                    }
                   /* if (!refundProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.REFUND_PRODUCT_LIST)) {
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case CUSTOMER:
                String cretorId = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerManagementEnum.CREATOR.getAttr(), "");
                if (StringUtil.isNotEmpty(cretorId)) {
                    // 客户创建人用逻辑创建人
                    handlerExplainDTO.setCreatorId(cretorId);
                }
                Integer isPublic = getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                // 查询此客户关联的退货退款
                Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                modelMap.put(ParameterConstant.CORPID, corpid);
                modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                Map<String, Object> dataParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                dataParam.put(RefundEnum.CUSTOMER_ID.getAttr(), paasFormDataEntityExt.getId());

                List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByCondition(XbbRefTypeEnum.REFUND.getCode(), dataParam, modelMap, IndexTypeEnum.IDX_SAAS_REFUND);
                //判断客户阶段是否开启
                boolean ifCustomerStageOpen = CommonHelp.ifStageOpen(businessType, explainMap, handlerExplainDTO);
                PaasMenuEntity customerQuotation = paasMenuModel.getByAlias(XbbRefTypeEnum.QUOTATION.getAlias(), null, corpid);
                boolean cusQuotationShow = customerQuotation != null && Objects.equals(customerQuotation.getEnable(), BasicConstant.ONE);
                // 判断电话字段是否可见
                boolean customerMobile = commonHelp.attrCanSee(CustomerManagementEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
                if(customerMobile){
                    List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(CustomerManagementEnum.PHONE.getAttr()).getSubForm().getItems();
                    Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
                    explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
                    boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
                    if(!text2CanSee){
                        customerMobile = false;
                    }
                }
                boolean parentCustomer = commonHelp.attrCanSee(CustomerManagementEnum.PARENT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (Objects.equals(isPublic, 1) && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_SALE_TEAM)) {
                        continue;
                    }
                    if (!isActiveCall && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_CALL_LOG)) {
                        continue;
                    }
                    if (paasFormDataEntityExts.isEmpty() && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_REFUND)) {
                        continue;
                    }
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_CUSTOMER_STAGE) && !ifCustomerStageOpen) {
                        continue;
                    }
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_QUOTATTIO) && !cusQuotationShow) {
                        continue;
                    }
                    if (!canSms && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    if (!parentCustomer && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_PARENT_AND_CHILD)) {
                        continue;
                    }
                    // 短信往来tab
                    if (!customerMobile && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    if ( !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) && !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) && Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_PAYMENT) ) {
                        continue;
                    }
                    // 非旗舰版，移动端没有联系人组织树
                    if (!ultimateType && Objects.equals(platFormEnum, PlatFormEnum.DINGTALK) && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_ORGANIZATION_TREE)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    //判断是否有回款单，是否有应收款、回款计划权限
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_PAYMENT) ) {
                        Boolean isHasPayment = false;
                        Boolean isHasPaymentSheet = false;
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) ) {
                            isHasPaymentSheet = true;
                        }
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) ) {
                            isHasPayment = true;
                        }
                        detailTabPojo.setIsHasPayment(isHasPayment);
                        detailTabPojo.setIsHasPaymentSheet(isHasPaymentSheet);
                    }
                    // web端联系人和组织树使用同一个tab，特殊处理
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_CONTACT_TAB)) {
                        detailTabPojo.setIsHasContactTree(ultimateType);
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if ( !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) && !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) && Objects.equals(tabEnum, BusinessDetailTabEnum.DISTRIBUTOR_PAYMENT) ) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    //判断是否有回款单，是否有应收款、回款计划权限
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.DISTRIBUTOR_PAYMENT) ) {
                        Boolean isHasPayment = false;
                        Boolean isHasPaymentSheet = false;
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) ) {
                            isHasPaymentSheet = true;
                        }
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) ) {
                            isHasPayment = true;
                        }
                        detailTabPojo.setIsHasPayment(isHasPayment);
                        detailTabPojo.setIsHasPaymentSheet(isHasPaymentSheet);
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case CLUE:
                Integer publicFlag = getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                //判断线索阶段是否开启
                boolean ifClueStageOpen = CommonHelp.ifStageOpen(businessType, explainMap, handlerExplainDTO);
                // 判断线索电话字段是否可见
                boolean clueMobile = commonHelp.attrCanSee(ClueEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
                if(clueMobile){
                    List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(ClueEnum.PHONE.getAttr()).getSubForm().getItems();
                    Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
                    explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
                    boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
                    if(!text2CanSee){
                        clueMobile = false;
                    }
                }
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (Objects.equals(publicFlag, 1) && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_SALE_TEAM)) {
                        continue;
                    }
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_STAGE) && !ifClueStageOpen) {
                        continue;
                    }
                    if (!isActiveCall && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_CALL_LOG)) {
                        continue;
                    }
                    if (!canSms && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    // 短信往来tab
                    if (!clueMobile && Objects.equals(tabEnum, BusinessDetailTabEnum.CLUE_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case MARKET_ACTIVITY:
                boolean closed4ClueMenu = marketManagementBusinessHelp.isClosed4ClueMenu(corpid);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    //线索菜单是关闭的，则不能有“活动成效”"销售线索"2个tab
                    if(closed4ClueMenu && (Objects.equals(BusinessDetailTabEnum.ACTIVITY_EFFECT,tabEnum) || Objects.equals(BusinessDetailTabEnum.SALE_CLUE,tabEnum))){
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case SALES_OPPORTUNITY:
                //判断客户阶段是否开启
                boolean ifOpportunityStageOpen = CommonHelp.ifStageOpen(businessType, explainMap, handlerExplainDTO);
                // 判断关联产品字段是否可见
//                boolean salesOpportunityProduct = commonHelp.attrCanSee(SalesOpportunityEnum.PRODUCTS.getAttr(), explainMap, handlerExplainDTO);
                PaasMenuEntity oppQuotation = paasMenuModel.getByAlias(XbbRefTypeEnum.QUOTATION.getAlias(), null, corpid);
                boolean oppQuotationShow = oppQuotation != null && Objects.equals(oppQuotation.getEnable(), BasicConstant.ONE);

                PaasMenuEntity oppContract = paasMenuModel.getByAlias(XbbRefTypeEnum.CONTRACT.getAlias(), null, corpid);
                boolean oppContractShow = oppContract != null && Objects.equals(oppContract.getEnable(), BasicConstant.ONE);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (!ifOpportunityStageOpen && Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_CUSTOMER_STAGE)) {
                        continue;
                    }
                    if (!oppContractShow && Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_CONTRACT)) {
                        // 合同菜单不开启，那么机会详情的合同tab也不开启
                        continue;
                    }
//                    if (!salesOpportunityProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_PRODUCT_LIST)) {
//                        continue;
//                    }
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_QUOTATION) && !oppQuotationShow) {
                        continue;
                    }
                    // 非旗舰版无机会联系人
                    if (!ultimateType && Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_CONTACT)) {
                        continue;
                    }
                    // 非旗舰版无竞争对手
                    if(!ultimateType &&  Objects.equals(tabEnum, BusinessDetailTabEnum.SALES_OPPORTUNITY_COMPETITOR)){
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    if (Objects.equals(DetailTabEnum.WORK_ORDER_LOG.getKey(), detailTabPojo.getAttr())) {
                        PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias(ChartCategoryAliasEnum.WORK_ORDER.getAlias(),corpid);
                        if (Objects.nonNull(paasMenuEntity)) {
                            detailTabPojo.setName(paasMenuEntity.getName());
                        }

                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case CONTACT:
                // 判断电话字段是否可见
                boolean contactMobile = commonHelp.attrCanSee(ContactEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
                if(contactMobile){
                    List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(ContactEnum.PHONE.getAttr()).getSubForm().getItems();
                    Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
                    explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
                    boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
                    if(!text2CanSee){
                        contactMobile = false;
                    }
                }
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (!isActiveCall && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_CALL_LOG)) {
                        continue;
                    }
                    if (!canSms && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    // 短信往来tab
                    if (!contactMobile && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case DISTRIBUTOR_CONTACT:
                // 判断电话字段是否可见
                boolean distributorContactMobile = commonHelp.attrCanSee(DistributorContactEnum.PHONE.getAttr(), explainMap, handlerExplainDTO);
                if(distributorContactMobile){
                    List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(DistributorContactEnum.PHONE.getAttr()).getSubForm().getItems();
                    Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
                    explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
                    boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
                    if(!text2CanSee){
                        contactMobile = false;
                    }
                }
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (!isActiveCall && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_CALL_LOG)) {
                        continue;
                    }
                    if (!canSms && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    // 短信往来tab
                    if (!distributorContactMobile && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTACT_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    detailTabPojo.setDistributorMark(distributorMark);
                    tabPojoList.add(detailTabPojo);
                }
                handelDetailPojo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(handelDetailPojo.getBusinessType()));
                break;
            case PURCHASE:
                Long returnedPurchaseId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormDataEntityExt.getData(), PurchaseEnum.RETURNED_PURCHASE_ID.getAttr(), 0L);
                // 判断关联产品字段是否可见
                //boolean productCansee = commonHelp.attrCanSee(PurchaseEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    //常驻，不然就要查数据库；现在returnedPurchaseId用来标记是否退完的
//                    if (returnedPurchaseId == 0L && Objects.equals(tabEnum, BusinessDetailTabEnum.PURCHASE_RETURNED_PURCHASE)) {
//                        continue;
//                    }
                   /* if(!productCansee && Objects.equals(tabEnum, BusinessDetailTabEnum.PURCHASE_PRODUCT_LIST)){
                        continue;
                    }*/
                    if (Objects.equals(tabEnum.getAnEnum().getKey(), DetailTabEnum.CONTRACT_COMPARE.getKey()) && !contractCompareUtil.showCompareTab(corpid, userVO.getPermSet(), userId)){
                        continue;
                    }
                    if ( !userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_SHEET_VIEW.getAlias()) && !userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_PLAN_VIEW.getAlias()) && Objects.equals(tabEnum, BusinessDetailTabEnum.PURCHASE_SUPPLIER_PAYMENT) ) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    //判断是否有付款单，是否有付款计划权限
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.PURCHASE_SUPPLIER_PAYMENT) ) {
                        Boolean isHasPayPlan = false;
                        Boolean isHasPaySheet = false;
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_SHEET_VIEW.getAlias()) ) {
                            isHasPaySheet = true;
                        }
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_PLAN_VIEW.getAlias()) ) {
                            isHasPayPlan = true;
                        }
                        detailTabPojo.setIsHasPayPlan(isHasPayPlan);
                        detailTabPojo.setIsHasPaySheet(isHasPaySheet);
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case INVOICE:
                Integer hasRed = getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), InvoiceEnum.HAS_RED.getAttr(), 0);
                Double totalRedMoney = 0D;
                if (Objects.equals(hasRed, BasicConstant.ONE)) {
                    totalRedMoney = invoiceModel.getRedTotalMoney(paasFormDataEntityExt.getId(), corpid);
                }
                boolean noRedInvoice = Objects.equals(hasRed, BasicConstant.ZERO) || totalRedMoney >= 0;
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (noRedInvoice && Objects.equals(tabEnum, BusinessDetailTabEnum.INVOICE_RED_INVOICE)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    detailTabPojo.setDistributorMark(distributorMark);
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case PURCHASE_INVOICE:
                Integer purchaseInvoiceHasRed = getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(),PurchaseInvoiceEnum.HAS_RED.getAttr(), 0);
                Double purchaseInvoiceTotalRedMoney = 0D;
                if (Objects.equals(purchaseInvoiceHasRed, BasicConstant.ONE)) {
                    purchaseInvoiceTotalRedMoney = purchaseInvoiceModel.getRedTotalMoney(paasFormDataEntityExt.getId(), corpid);
                }
                boolean noRedPurchaseInvoice = Objects.equals(purchaseInvoiceHasRed, BasicConstant.ZERO) || purchaseInvoiceTotalRedMoney >= 0;
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (noRedPurchaseInvoice && Objects.equals(tabEnum, BusinessDetailTabEnum.PURCHASE_INVOICE_RED_INVOICE)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case PRODUCT:
                // 查询此产品关联的退货退款(退货退款关联的是子产品id)
                BoolQueryBuilder productBuilder = boolQuery();
                productBuilder.filter(termQuery("corpid.keyword", corpid));
                productBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                productBuilder.filter(termsQuery("data." + ProductEnum.PARENT_ID.getAttr(), Arrays.asList(paasFormDataEntityExt.getId())));
                List<ProductEntityExt> productEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, productBuilder, ProductEntityExt.class, Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
                List<Long> childProductIds = new ArrayList<>();
                childProductIds.add(-1L);
                productEntityExtList.forEach(entityExt -> childProductIds.add(entityExt.getDataId()));

                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termsQuery("data." + RefundEnum.PRODUCTS.getAttr(), childProductIds));
                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_REFUND.getType()));
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                sourceBuilder.query(boolQueryBuilder);
                SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_REFUND.getIndex());
                searchRequest.source(sourceBuilder);
                Long count = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);
                boolean noRefund = count == null || count == 0;
                Boolean batchShelf = companyConfigModel.getBatchShelf(corpid);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (noRefund && Objects.equals(tabEnum, BusinessDetailTabEnum.PRODUCT_REFUND)) {
                        continue;
                    }
                    if (!batchShelf && (Objects.equals(tabEnum, BusinessDetailTabEnum.PRODUCT_BATCH_TAB) || Objects.equals(tabEnum, BusinessDetailTabEnum.PRODUCT_GUARANTEE_TAB))) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                // 判断关联产品字段是否可见
                //boolean outstockProduct = commonHelp.attrCanSee(OutstockEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    /*if(!outstockProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.OUTSTOCK_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                // 判断关联产品字段是否可见
               // boolean instockProduct = commonHelp.attrCanSee(InstockEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if(!instockProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.INSTOCK_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case SUPPLIER:
                // 判断关联产品字段是否可见
                //boolean supplierProduct = commonHelp.attrCanSee(SupplierEnum.PRODUCT_LIST.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if(!supplierProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_PRODUCT_LIST)){
                        continue;
                    }*/
                    if ( !userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_SHEET_VIEW.getAlias()) && !userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_PLAN_VIEW.getAlias()) && Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_SUPPLIER_PAYMENT) ) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    //判断是否有付款单，是否有付款计划权限
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_SUPPLIER_PAYMENT) ) {
                        Boolean isHasPayPlan = false;
                        Boolean isHasPaySheet = false;
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_SHEET_VIEW.getAlias()) ) {
                            isHasPaySheet = true;
                        }
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAY_PLAN_VIEW.getAlias()) ) {
                            isHasPayPlan = true;
                        }
                        detailTabPojo.setIsHasPayPlan(isHasPayPlan);
                        detailTabPojo.setIsHasPaySheet(isHasPaySheet);
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case RETURNED_PURCHASE:
                // 判断关联产品字段是否可见
                //boolean returnedPurchaseProduct = commonHelp.attrCanSee(ReturnedPurchaseEnum.PRODUCTS.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if(!returnedPurchaseProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.RETURNED_PURCHASE_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case BOMBILL:
                // 判断关联产品字段是否可见(成品和物料同时不在)
                //boolean product = commonHelp.attrCanSee(BomBillEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                //boolean materiel = commonHelp.attrCanSee(BomBillEnum.MATERIEL.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    /*if(!product && !materiel && Objects.equals(tabEnum, BusinessDetailTabEnum.BOM_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case PRODUCTIONORDER:
                // 判断关联产品字段是否可见(成品和物料同时不在)
                boolean noInStockTabPer = !userVO.getPermSet().contains(ProPermissionAliasEnum.PRODUCTION_INSTOCK_VIEW.getAlias())
                        && !userVO.getPermSet().contains(ProPermissionAliasEnum.RETURNED_MATERIEL_INSTOCK_VIEW.getAlias());
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   if (noInStockTabPer && Objects.equals(tabEnum, BusinessDetailTabEnum.PRODUCTION_ORDER_INSTOCK_TAB)) {
                       continue;
                   }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case INVENTORY:
                // 判断关联产品字段是否可见
                //boolean inventoryProduct = commonHelp.attrCanSee(InventoryEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if(!inventoryProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.INVENTORY_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case TRANSFER:
                // 判断关联产品字段是否可见
                //boolean transferProduct = commonHelp.attrCanSee(TransferEnum.PRODUCTS.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if(!transferProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.TRANSFER_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case ASSEMBLE:
                // 判断关联产品字段是否可见
                //boolean outProduct = commonHelp.attrCanSee(AssembleEnum.OUT_PRODUCTS.getAttr(), explainMap, handlerExplainDTO);
                //boolean inProduct = commonHelp.attrCanSee(AssembleEnum.IN_PRODUCTS.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if(!outProduct && !inProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.ASSEMBLE_INSTOCK_OUTSTOCK_PRODUCT_LIST)){
                        continue;
                    }*/
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case PAYMENT_SHEET:
                //获取当前处于什么模式
                Long nowMmodelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
                //对于应收款 回款单数据,列表中既有模式一数据,又有模式二数据,获取数据的模式
                boolean invoiceModelFlag = fundSetHelp.checkInvoiceModelFlag(modelType, nowMmodelType);
                //回款单类型
                String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.WRITE_OFF.getCode());
                boolean prepayment = Objects.equals(paymentSheetType, PaymentSheetTypeEnum.PREPAYMENT.getCode());
                boolean writeOffPrepayment = Objects.equals(paymentSheetType, PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT.getCode());
                boolean redBadFlag = PaymentSheetTypeEnum.isRed(paymentSheetType) || PaymentSheetTypeEnum.isBad(paymentSheetType);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (invoiceModelFlag && Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SHEET_INVOICE_HISTORY)) {
                        //开票模式，回款单详情页无“开票历史”tab
                        continue;
                    }
                    if (writeOffPrepayment && Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SHEET_INVOICE_HISTORY)) {
                        //预收款核销：无开票历史tab
                        continue;
                    }
                    if (prepayment && Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SHEET_RED_HISTORY)) {
                        //预收款：无红冲记录tab
                        continue;
                    }
                    boolean flag = redBadFlag && (Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SHEET_INVOICE_HISTORY) || Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SHEET_RED_HISTORY));
                    if (flag) {
                        //红冲、坏账：无开票历史、无红冲记录tab
                        continue;
                    }
                    if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)
                            && Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SHEET_SALE_TEAM)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    detailTabPojo.setDistributorMark(distributorMark);
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case PAY_SHEET:
                //付款单类型
                String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                prepayment = Objects.equals(paySheetType, PaySheetTypeEnum.PREPAY.getCode());
                writeOffPrepayment = Objects.equals(paySheetType, PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode());
                redBadFlag = PaySheetTypeEnum.isRed(paySheetType) || PaySheetTypeEnum.isBad(paySheetType);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (writeOffPrepayment && Objects.equals(tabEnum, BusinessDetailTabEnum.PAY_SHEET_INVOICE_HISTORY)) {
                        //预付款核销：无开票历史tab
                        continue;
                    }
                    if (prepayment && Objects.equals(tabEnum, BusinessDetailTabEnum.PAY_SHEET_RED_HISTORY)) {
                        //预付款：无红冲记录tab
                        continue;
                    }
                    boolean flag = redBadFlag && (Objects.equals(tabEnum, BusinessDetailTabEnum.PAY_SHEET_INVOICE_HISTORY) || Objects.equals(tabEnum, BusinessDetailTabEnum.PAY_SHEET_RED_HISTORY));
                    if (flag) {
                        //红冲、坏账：无开票历史、无红冲记录tab
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case WORKORDER:
                // 判断电话字段是否可见
                boolean workOrderMobile = commonHelp.attrCanSee(WorkOrderEnum.CONTACT_INFORMATION.getAttr(), explainMap, handlerExplainDTO);
                if(workOrderMobile){
                    List<? extends FieldAttrEntity> explainSubFormList = explainMap.get(WorkOrderEnum.CONTACT_INFORMATION.getAttr()).getSubForm().getItems();
                    Map<String, FieldAttrEntity> explainSubFormMap = new HashMap<>(explainSubFormList.size());
                    explainSubFormList.forEach((item) -> explainSubFormMap.put(item.getAttr(), item));
                    boolean text2CanSee = commonHelp.attrCanSee(StringConstant.PHONE_TEL_ATTR, explainSubFormMap, handlerExplainDTO);
                    if(!text2CanSee){
                        workOrderMobile = false;
                    }
                }
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (!canSms && Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_ORDER_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    // 短信往来tab
                    if (!workOrderMobile && Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_ORDER_SMS_SEND_AND_REPLY)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case REIMBURSEMENT_FORM:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {

                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.EXPENSE_LIST)) {
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.EXPENSE.getCode(), corpid);
                        if (Objects.nonNull(paasFormEntityExt)) {
                            detailTabPojo.setKey(DetailTabEnum.LINK_LIST.getKey());
                            LinkListPojo linkList = new LinkListPojo();
                            linkList.setAttr(ExpenseEnum.REIMBURSEMENT_FORM_ID.getAttr());
                            linkList.setEnable(1);
                            linkList.setLinkAppId(paasFormEntityExt.getAppId());
                            linkList.setLinkBusinessType(XbbRefTypeEnum.EXPENSE.getCode());
                            linkList.setLinkFormId(paasFormEntityExt.getId());
                            linkList.setLinkMenuId(paasFormEntityExt.getMenuId());
                            linkList.setLinkSaasMark(SaasMarkEnum.SAAS.getCode());
                            detailTabPojo.setLinkList(linkList);
                        }
                    }

                    tabPojoList.add(detailTabPojo);
                }
                break;
            //跟进记录
            case COMMUNICATE:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_COMMENT)
                            || Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_LIKE)){
                        BusinessCommentEnum businessCommentEnum = BusinessCommentEnum.getByBusinessType(businessType);
                        if (businessCommentEnum == null) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
                        }
                        Map<String, Object> commentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        commentMap.put("type", businessCommentEnum.getCode());
                        commentMap.put("corpid",corpid);
                        commentMap.put("refId",paasFormDataEntityExt.getDataId());
                        commentMap.put("del",0);
                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_COMMENT)){
                            Integer countNum = paasCommentModel.getEntitysCount(commentMap);
                            detailTabPojo.setCommentCount(countNum);
                        }

                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.CUSTOMER_COMMUNICATE_LIKE)){
                            Integer likeNum = likeModel.getEntitysCount(commentMap);
                            detailTabPojo.setLikeCount(likeNum);
                        }
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case DISTRIBUTOR_COMMUNICATE:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.DISTRIBUTOR_COMMUNICATE_COMMENT)
                            || Objects.equals(tabEnum, BusinessDetailTabEnum.DISTRIBUTOR_COMMUNICATE_LIKE)){
                        Map<String, Object> commentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        commentMap.put("type", BusinessCommentEnum.CUSTOMER_COMMUNICATE.getCode());
                        commentMap.put("corpid",corpid);
                        commentMap.put("refId",paasFormDataEntityExt.getDataId());
                        commentMap.put("del",0);
                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.DISTRIBUTOR_COMMUNICATE_COMMENT)){
                            Integer countNum = paasCommentModel.getEntitysCount(commentMap);
                            detailTabPojo.setCommentCount(countNum);
                        }

                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.DISTRIBUTOR_COMMUNICATE_LIKE)){
                            Integer likeNum = likeModel.getEntitysCount(commentMap);
                            detailTabPojo.setLikeCount(likeNum);
                        }
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            //工作日报
            case WORKREPORT:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_COMMENT)
                            || Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_LIKE)){
                        BusinessCommentEnum businessCommentEnum = BusinessCommentEnum.getByBusinessType(businessType);
                        if (businessCommentEnum == null) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
                        }
                        Map<String, Object> commentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        commentMap.put("type", businessCommentEnum.getCode());
                        commentMap.put("corpid",corpid);
                        commentMap.put("refId",paasFormDataEntityExt.getDataId());
                        commentMap.put("del",0);
                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_COMMENT)){
                            Integer countNum = paasCommentModel.getEntitysCount(commentMap);
                            detailTabPojo.setCommentCount(countNum);
                        }

                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.WORK_REPORT_LIKE)){
                            Integer likeNum = likeModel.getEntitysCount(commentMap);
                            detailTabPojo.setLikeCount(likeNum);
                        }
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            //供应商跟进记录
            case JXC_COMMUNICATE:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_COMMUNICATE_COMMENT)
                            || Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_COMMUNICATE_LIKE)){
                        BusinessCommentEnum businessCommentEnum = BusinessCommentEnum.getByBusinessType(businessType);
                        if (businessCommentEnum == null) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
                        }
                        Map<String, Object> commentMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        commentMap.put("type", businessCommentEnum.getCode());
                        commentMap.put("corpid",corpid);
                        commentMap.put("refId",paasFormDataEntityExt.getDataId());
                        commentMap.put("del",0);
                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_COMMUNICATE_COMMENT)){
                            Integer countNum = paasCommentModel.getEntitysCount(commentMap);
                            detailTabPojo.setCommentCount(countNum);
                        }

                        if (Objects.equals(tabEnum, BusinessDetailTabEnum.SUPPLIER_COMMUNICATE_LIKE)){
                            Integer likeNum = likeModel.getEntitysCount(commentMap);
                            detailTabPojo.setLikeCount(likeNum);
                        }
                    }
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case OTHER_INCOME:
                //其他收入单类型
                String otherIncomeSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr(), OtherIncomeSheetTypeEnum.OTHER_INCOME.getCode());
                boolean redFlag = OtherIncomeSheetTypeEnum.isRed(otherIncomeSheetType);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    boolean flag = redFlag && Objects.equals(tabEnum, BusinessDetailTabEnum.OTHER_INCOME_RED_HISTORY);
                    if (flag) {
                        //红冲：无红冲记录tab
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case OTHER_EXPENSE:
                //其他支出单类型
                String otherExpenseSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr(), OtherExpenseSheetTypeEnum.OTHER_EXPENSE.getCode());
                redFlag = OtherExpenseSheetTypeEnum.isRed(otherExpenseSheetType);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    boolean flag = redFlag && Objects.equals(tabEnum, BusinessDetailTabEnum.OTHER_EXPENSE_RED_HISTORY);
                    if (flag) {
                        //红冲：无红冲记录tab
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case PAYMENT:
                String paymentType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentEnum.STATUS.getAttr(),PaymentStatusEnum.UN_RECEIVABLES.getCode());
                Integer isRed = FastJsonHelper.getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), PaymentEnum.RECEIVABLE_IS_RED.getAttr(),BasicConstant.ZERO);
                //获取当前处于什么模式
                nowMmodelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
                //对于应收款 回款单数据,列表中既有模式一数据,又有模式二数据,获取数据的模式
                invoiceModelFlag = fundSetHelp.checkInvoiceModelFlag(modelType, nowMmodelType);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if(Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_RED_HISTORY) || Objects.equals(tabEnum,BusinessDetailTabEnum.PAYMENT_PAYMENT_SHEET)){
                        if(Objects.equals(paymentType,PaymentStatusEnum.RED_RECEIVABLES.getCode()) && Objects.equals(isRed,BasicConstant.ONE)){
                            continue;
                        }
                    }
                    if (invoiceModelFlag && Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_INVOICE_HISTORY)) {
                        continue;
                    }
                    if (Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)
                            && Objects.equals(tabEnum, BusinessDetailTabEnum.PAYMENT_SALE_TEAM)) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    detailTabPojo.setDistributorMark(distributorMark);
                    tabPojoList.add(detailTabPojo);
                }

                break;
            case CREDIT_LIMIT:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case ORDER:
//                openDistribution = contractPerformanceService.openDistribution(corpid);
                // 判断关联产品字段是否可见
                // contractProduct = commonHelp.attrCanSee(OrderEnum.PRODUCT.getAttr(), explainMap, handlerExplainDTO);
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                   /* if (!contractProduct && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_PRODUCT_LIST)) {
                        continue;
                    }*/
                    // hasRed = saasUpdateHelp.getIntegerOrDefaultFromFormData(paasFormDataEntityExt.getData(), OrderEnum.HAS_RED.getAttr(), BasicConstant.ZERO);
                    /*if (!Objects.equals(hasRed, BasicConstant.ONE) && Objects.equals(tabEnum, BusinessDetailTabEnum.CONTRACT_REFUND)) {
                        continue;
                    }*/
                    if ( !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) && !userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) && Objects.equals(tabEnum, BusinessDetailTabEnum.ORDER_PAYMENT) ) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    //判断是否有回款单，是否有应收款、回款计划权限
                    if ( Objects.equals(tabEnum, BusinessDetailTabEnum.ORDER_PAYMENT) ) {
                        Boolean isHasPayment = false;
                        Boolean isHasPaymentSheet = false;
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_SHEET_VIEW.getAlias()) ) {
                            isHasPaymentSheet = true;
                        }
                        if ( userVO.getPermSet().contains(ProPermissionAliasEnum.PAYMENT_VIEW.getAlias()) ) {
                            isHasPayment = true;
                        }
                        detailTabPojo.setIsHasPayment(isHasPayment);
                        detailTabPojo.setIsHasPaymentSheet(isHasPaymentSheet);
                        detailTabPojo.setDistributorMark(distributorMark);
                    }
                    tabPojoList.add(detailTabPojo);
                }
                handelDetailPojo.setBusinessType(XbbRefTypeEnum.transferBusinessType2Index(businessType));
                break;
            case COMPETITOR:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
            default:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    changeTabEnumName(paasBusinessTypeToName, tabEnum, detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
        }
        handleTeamTab(tabPojoList, explainMap);
    }

    /**
     * 如果菜单名字改变,修改相应的表单名字
     * @param paasBusinessTypeToName
     * @param tabEnum
     * @param detailTabPojo
     */
    private void changeTabEnumName(HashMap<Integer, String> paasBusinessTypeToName, BusinessDetailTabEnum tabEnum, DetailTabPojo detailTabPojo) {
        if (tabEnum.getFormBusinessType() != 0
                && Objects.nonNull(paasBusinessTypeToName.get(tabEnum.getFormBusinessType()))
                && !Objects.equals(paasBusinessTypeToName.get(tabEnum.getFormBusinessType()), XbbRefTypeEnum.getByCode(tabEnum.getFormBusinessType()).getName())) {
            detailTabPojo.setName(paasBusinessTypeToName.get(tabEnum.getFormBusinessType()));
        }
    }

    /**
     * 处理详情头部关注按钮
     *
     * @param businessType          业务类型
     * @param titlePojo             标题
     * @param paasFormDataEntityExt 数据实体
     * @param userId                登陆人
     */
    public void handelDetailFocus(Integer businessType, DetailTitlePojo titlePojo, PaasFormDataEntityExt paasFormDataEntityExt, String userId) {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        Integer isFocus = BasicConstant.NO_USE;
        Long id = paasFormDataEntityExt.getId();
        String corpid = paasFormDataEntityExt.getCorpid();
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                //关注
                boolean isCusShare;
                try {
                    isCusShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getAlias(), BasicConstant.IS_USE.toString());
                } catch (XbbException e) {
                    isCusShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_CUSTOEMR.getValue(), BasicConstant.IS_USE.toString());
                }
                Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                if (!isCusShare) {
                    map.put("userId", userId);
                }
                map.put("customerIdIn", Collections.singletonList(id));
                map.put("del", DelEnum.NORMAL.getDel());
                map.put("focus", BasicConstant.IS_USE);
                List<CustomerFocusEntity> customerFocusEntityList = customerFocusModel.findEntitys(map);
                isFocus = customerFocusEntityList != null && customerFocusEntityList.size() > 0 ? BasicConstant.IS_USE : BasicConstant.NO_USE;
                break;
            case SALES_OPPORTUNITY:
                boolean isOppShare;
                try {
                    isOppShare = companyConfigModel.hasBeenEnable(corpid, CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getAlias(), BasicConstant.IS_USE.toString());
                } catch (XbbException e) {
                    isOppShare = Objects.equals(CompanyConfigEnum.SHARE_FOCUS_OPPORTUNITY.getValue(), BasicConstant.IS_USE.toString());
                }
                map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                map.put("corpid", corpid);
                if (!isOppShare) {
                    map.put("userId", userId);
                }
                map.put("opportunityIdIn", Collections.singletonList(id));
                map.put("del", DelEnum.NORMAL.getDel());
                map.put("focus", BasicConstant.IS_USE);
                List<OpportunityFocusEntity> opportunityFocusEntityList = opportunityFocusModel.findEntitys(map);
                isFocus = opportunityFocusEntityList != null && opportunityFocusEntityList.size() > 0 ? BasicConstant.IS_USE : BasicConstant.NO_USE;
                break;
            default:
                break;
        }
        titlePojo.setIsFocus(isFocus);
    }

    /**
     * 加载二级标题（详情摘要）
     *
     * @param businessType          业绩类型
     * @param secondTitle           二级标题
     * @param paasFormDataEntityExt 业务实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-17 10:39
     * @version v1.0
     * @since v1.0
     */
    public void handelDetailSecondTitle(Integer businessType, JSONArray secondTitle, PaasFormDataEntityExt paasFormDataEntityExt,
                                        Map<String, FieldAttrEntity> explainMap) throws XbbException {
        JSONObject dataList = paasFormDataEntityExt.getData();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        Long dataId = paasFormDataEntityExt.getId();
        String corpid = paasFormDataEntityExt.getCorpid();
        // 更新时间
        String updateTimeStr = DateUtil.getString(paasFormDataEntityExt.getUpdateTime() * 1000, DateUtil.SDFYMDHM);
        // 负责人
        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        String managerName = "";
        if (userTeamEnum == UserTeamEnum.UNKNOW) {
            UserEntity managerEntity = userModel.getByKey(paasFormDataEntityExt.getOwnerId(), corpid);
            managerName = managerEntity != null ? managerEntity.getName() : "";
        } else {
            Map<Long, String> userTeamMap = userTeamService.getMainUserMap(Collections.singletonList(dataId), corpid, businessType, false);
            if (userTeamMap.containsKey(dataId)) {
                managerName = userTeamMap.get(dataId);
            }
        }

        switch (xbbRefTypeEnum) {
            // 客户
            case CUSTOMER_MANAGEMENT:
                // 客户状态，最后跟进时间，当前阶段停留时长(仅设置了阶段的情况下显示)
                Integer lastConnectTime = getIntegerFromFormData(dataList, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr());
                String lastConnectTimeStr = DateUtil.getString(lastConnectTime, DateUtil.SDFYMDHM);
                if (StringUtil.isEmpty(lastConnectTimeStr)) {
                    lastConnectTimeStr = I18nMessageUtil.getMessage(CommonConstant.NOTHING);
                }
                String type = FastJsonHelper.getStringFromFormData(dataList, CustomerManagementEnum.TYPE.getAttr());
                CustomerTypeEnum typeEnum = CustomerTypeEnum.getByCode(type);
                String typeStr = typeEnum != null ? typeEnum.getName() : "";
                String cStayTimeStr = customerStageLogModel.getAverageStayTime(corpid, dataId, paasFormDataEntityExt.getFormId());

                // 前端展示

                JSONObject cusObj1 = ExplainUtil.getSecondTitleObj(false, CustomerManagementEnum.TYPE.getAttrName(), typeStr);
                JSONObject cusObj2 = ExplainUtil.getSecondTitleObj(false, CustomerManagementEnum.LAST_CONNECT_TIME.getAttrName(), lastConnectTimeStr);
                secondTitle.add(cusObj1);
                secondTitle.add(cusObj2);
                if (cStayTimeStr != null) {
                    JSONObject cusObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.CURRENT_STAGE_LONG), cStayTimeStr);
                    secondTitle.add(cusObj3);
                }
                break;
            // 联系人
            case CONTACT:
                // 更新时间
                JSONObject contactObj = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(contactObj);
                break;
            // 访客计划
            case COMMUNICATE_PLAN:
                // 执行人、客户状态、访客执行时间
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put(ParameterConstant.CORPID, corpid);
                param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                param.put("planId", dataId);
                List<CommunicatePlanUserEntity> communicatePlanUserEntityList = communicatePlanUserModel.findEntitys(param);
                StringBuilder executorName = new StringBuilder();
                communicatePlanUserEntityList.forEach(communicatePlanUserEntity -> executorName.append(communicatePlanUserEntity.getUserName()).append(StringConstant.COMMA));
                if (!communicatePlanUserEntityList.isEmpty()) {
                    executorName.deleteCharAt(executorName.length() - 1);
                }
                Long customerId = FastJsonHelper.getLongFromFormData(dataList, CommunicatePlanEnum.LINK_CUSTOMER.getAttr());
                PaasFormDataEntityExt customerExt = customerModel.getByKey(customerId, corpid);
                String customerType = FastJsonHelper.getStringFromFormData(customerExt.getData(), CustomerManagementEnum.TYPE.getAttr());
                CustomerTypeEnum customerTypeEnum = CustomerTypeEnum.getByCode(customerType);
                String customerTypeStr = customerTypeEnum != null ? customerTypeEnum.getName() : "";
                Integer communicateTime = getIntegerFromFormData(dataList, CommunicatePlanEnum.COMMUNICATE_TIME.getAttr());
                String communicateTimeStr = DateUtil.getString(communicateTime, DateUtil.SDFYMDHM);
                // 前端展示
                JSONObject commPlanObj1 = ExplainUtil.getSecondTitleObj(true, I18nMessageUtil.getMessage(I18nStringConstant.EXECUTIVE), executorName.toString());
                JSONObject commPlanObj2 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_STATUS), customerTypeStr);
                JSONObject commPlanObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.VISIT_EXECUTE_TIME), communicateTimeStr);

                secondTitle.add(commPlanObj1);
                secondTitle.add(commPlanObj2);
                secondTitle.add(commPlanObj3);
                break;
            // 销售机会
            case SALES_OPPORTUNITY:
                // 关联客户、预计金额、当前阶段停留时长(仅设置了阶段的情况下显示)、预计结束日期
                String customerName = FastJsonHelper.getStringFromFormData(dataList, SalesOpportunityEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
                FieldAttrEntity estimateAmountAttrEntity = explainMap.get(SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr());
                Double estimateAmount;
                try {
                    estimateAmount = getDoubleFromFormData(dataList, SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttr());
                } catch (XbbException e) {
                    estimateAmount = 0D;
                }
                // 小数精度
                Integer esAmountAccuracy = estimateAmountAttrEntity != null ? estimateAmountAttrEntity.getAccuracy() : null;
                Integer amoutFlag = estimateAmountAttrEntity != null ? estimateAmountAttrEntity.getAmountFlag() : null;
                Object estimateAmountObj;
                if (Objects.equals(AmountFlagEnum.YES.getType(), amoutFlag)) {
                    estimateAmountObj = AttrDecimalPrecisionHelper.parseThousandth(estimateAmount, esAmountAccuracy);
                } else {
                    estimateAmountObj = attrDecimalPrecisionHelper.setPrecision(estimateAmount, esAmountAccuracy);
                }
                String opStayTimeStr = opportunityStageLogModel.getAverageStayTime(corpid, dataId, paasFormDataEntityExt.getFormId());
                Integer estimateEndTime = getIntegerFromFormData(dataList, SalesOpportunityEnum.ESTIMATE_END_TIME.getAttr());
                String estimateEndTimeStr = DateUtil.getString(estimateEndTime, DateUtil.SDFDate);
                // 前端展示
                JSONObject opporObj1 = ExplainUtil.getSecondTitleObj(false, SalesOpportunityEnum.CUSTOMER_NAME.getAttrName(), customerName);
                JSONObject opporObj2 = ExplainUtil.getSecondTitleObj(false, SalesOpportunityEnum.ESTIMATE_AMOUNT.getAttrName(), estimateAmountObj);
                secondTitle.add(opporObj1);
                secondTitle.add(opporObj2);

                if (opStayTimeStr != null) {
                    JSONObject opporObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.STAY_LONG_TIME), opStayTimeStr);
                    secondTitle.add(opporObj3);
                }

                JSONObject opporObj4 = ExplainUtil.getSecondTitleObj(false, SalesOpportunityEnum.ESTIMATE_END_TIME.getAttrName(), estimateEndTimeStr);
                secondTitle.add(opporObj4);
                break;
            // 合同
            case CONTRACT:
                // 负责人、签订日期
                Integer contractSignTime = getIntegerFromFormData(dataList, ContractEnum.SIGN_TIME.getAttr());
                String contractSignTimeStr = DateUtil.getString(contractSignTime, DateUtil.SDFDate);
                JSONObject contractObj1 = ExplainUtil.getSecondTitleObj(true, ContractEnum.OWNER_ID.getAttrName(), managerName);
                JSONObject contractObj2 = ExplainUtil.getSecondTitleObj(false, ContractEnum.SIGN_TIME.getAttrName(), contractSignTimeStr);
                secondTitle.add(contractObj1);
                secondTitle.add(contractObj2);
                break;
            case REFUND:
                Integer refundSignTime = getIntegerFromFormData(dataList, RefundEnum.SIGN_DATE.getAttr());
                String redundSignTimeStr = DateUtil.getString(refundSignTime, DateUtil.SDFDate);

                JSONObject refundObj1 = ExplainUtil.getSecondTitleObj(true, RefundEnum.OWNER_ID.getAttrName(), managerName);
                JSONObject refundObj2 = ExplainUtil.getSecondTitleObj(false, RefundEnum.SIGN_DATE.getAttrName(), redundSignTimeStr);
                secondTitle.add(refundObj1);
                secondTitle.add(refundObj2);
                break;

            // 应收款
            case PAYMENT:
                // 负责人、关联合同
                String contractName = FastJsonHelper.getStringFromFormData(dataList, PaymentEnum.CONTRACT_LINK_TEXT.getAttr());
                JSONObject paymentObj1 = ExplainUtil.getSecondTitleObj(true, PaymentEnum.OWNER_ID.getAttrName(), managerName);
                JSONObject paymentObj2 = ExplainUtil.getSecondTitleObj(false, PaymentEnum.CONTRACT.getAttrName(), contractName);
                secondTitle.add(paymentObj1);
                secondTitle.add(paymentObj2);
                break;
            // 付款计划
            case PAY_PLAN:
                // 负责人、关联采购合同
                String purchaseName = FastJsonHelper.getStringFromFormData(dataList, PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr());
                JSONObject payPlanObj1 = ExplainUtil.getSecondTitleObj(true, PayPlanEnum.OWNER_ID.getAttrName(), managerName);
                JSONObject payPlanObj2 = ExplainUtil.getSecondTitleObj(false, PayPlanEnum.LINK_PURCHASE.getAttrName(), purchaseName);
                secondTitle.add(payPlanObj1);
                secondTitle.add(payPlanObj2);
                break;
            // 发票管理
            case INVOICE:
                //开票金额、开票日期
                Double totalMoney = getDoubleFromFormData(dataList, InvoiceEnum.TOTAL_MONEY.getAttr());

                Double totalRedMoney = 0D;
                Integer hasRedInt = getIntegerFromFormData(dataList, InvoiceEnum.HAS_RED.getAttr());
                boolean hasRed = Objects.equals(hasRedInt, 1);
                /*
                 * 查询原发票关联的红冲发票
                 */
                if (hasRed) {
                    totalRedMoney = invoiceModel.getRedTotalMoney(dataId, corpid);

                }
                // 小数精度
                FieldAttrEntity invoiceFieldAttrEntity = explainMap.get(InvoiceEnum.TOTAL_MONEY.getAttr());
                Integer invoiceMoneyAccuracy = invoiceFieldAttrEntity != null ? invoiceFieldAttrEntity.getAccuracy() : null;
                Integer amountFlag = invoiceFieldAttrEntity != null ? invoiceFieldAttrEntity.getAmountFlag() : null;
                Object totalMoneyObj;
                Object totalRedMoneyObj;
                if (Objects.equals(AmountFlagEnum.YES.getType(), amountFlag)) {
                    totalMoneyObj = AttrDecimalPrecisionHelper.parseThousandth(totalMoney, invoiceMoneyAccuracy);
                    totalRedMoneyObj = AttrDecimalPrecisionHelper.parseThousandth(totalRedMoney, invoiceMoneyAccuracy);
                } else {
                    totalMoneyObj = attrDecimalPrecisionHelper.setPrecision(totalMoney, invoiceMoneyAccuracy);
                    totalRedMoneyObj = attrDecimalPrecisionHelper.setPrecision(totalRedMoney, invoiceMoneyAccuracy);
                }
                Integer invoiceDate = getIntegerFromFormData(dataList, InvoiceEnum.INVOICE_DATE.getAttr());
                String invoiceDateStr = DateUtil.getString(invoiceDate, DateUtil.SDFDate);
                JSONObject invoiceObj1 = ExplainUtil.getSecondTitleObj(false, InvoiceEnum.TOTAL_MONEY.getAttrName(), totalMoneyObj + I18nMessageUtil.getMessage(CommonConstant.YUAN));
                secondTitle.add(invoiceObj1);
                if (hasRed && !Objects.equals(totalRedMoney, BasicConstant.ZERO_DOUBLE)) {
                    JSONObject invoiceObj2 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.RED_INVOICE_MONEY), totalRedMoneyObj + I18nMessageUtil.getMessage(CommonConstant.YUAN));
                    secondTitle.add(invoiceObj2);
                }
                JSONObject invoiceObj3 = ExplainUtil.getSecondTitleObj(false, InvoiceEnum.INVOICE_DATE.getAttrName(), invoiceDateStr);
                secondTitle.add(invoiceObj3);
                break;

            // 供应商、供应商联系人、采购合同、采购退货、入库单、出库单、盘点单、调拔单、装配出入库单
            case SUPPLIER:
            case SUPPLIER_CONTACT:
                //更新时间
                JSONObject supplierContactObj = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(supplierContactObj);
                break;
            case PURCHASE:
            case RETURNED_PURCHASE:
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case TRANSFER:
            case INVENTORY:
            case ASSEMBLE:
                // 负责人、更新时间
                JSONObject jxcObj1 = ExplainUtil.getSecondTitleObj(true, AssembleEnum.MANAGER_ID.getAttrName(), managerName);
                JSONObject jxcObj2 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(jxcObj1);
                secondTitle.add(jxcObj2);
                break;

            case WAREHOUSE:
                // 负责人、负责部门、最新更新时间
                Map<Long, String> warehouserUserTeamMap = userTeamService.getProductUserMap(Collections.singletonList(dataId), corpid, businessType, 0);
                managerName = warehouserUserTeamMap.containsKey(dataId) ? warehouserUserTeamMap.get(dataId) : "";
                JSONObject warehouseObj1 = ExplainUtil.getSecondTitleObj(true, WarehouseEnum.MANAGER_ID.getAttrName(), managerName);
                JSONObject warehouseObj2 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(warehouseObj1);
                secondTitle.add(warehouseObj2);
                break;

            // 产品
            case PRODUCT:
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                // 如果是子产品则拿他的父产品id
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.mustNot(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID), 0));
                boolQueryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), dataId));
                sourceBuilder.query(boolQueryBuilder);
                XbbAggregatedPage esEntities = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, Collections.singletonList(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID)), 1, 1, null);
                if (esEntities == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                List<PaasFormDataEntityExt> resultList =  esEntities.getContent();
                if(CollectionsUtil.isNotEmpty(resultList)){
                    dataId = resultList.get(0).getData().getLong(ProductEnum.PARENT_ID.getAttr());
                }

                // 负责人、负责部门、最新更新时间
                Map<Long, String> productUserTeamMap = userTeamService.getProductUserMap(Collections.singletonList(dataId), corpid, businessType, 0);
                Map<Long, String> productDepTeamMap = userTeamService.getProductUserMap(Collections.singletonList(dataId), corpid, businessType, 1);
                managerName = productUserTeamMap.containsKey(dataId) ? productUserTeamMap.get(dataId) : "";
                String productDepTeamName = productDepTeamMap.containsKey(dataId) ? productDepTeamMap.get(dataId) : "";
                JSONObject productObj1 = ExplainUtil.getSecondTitleObj(true, I18nMessageUtil.getMessage(TabConstant.MAIN_USER_ATTR_NAME), managerName);
                JSONObject productObj2 = ExplainUtil.getSecondTitleObj(true, I18nMessageUtil.getMessage(I18nStringConstant.MAIN_DEPARTMENT), productDepTeamName);
                JSONObject productObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(productObj1);
                secondTitle.add(productObj2);
                secondTitle.add(productObj3);
                break;
            // BOM清单
            case BOM_BILL:
                // 状态、修改时间
                Integer bomStatus = getIntegerFromFormData(dataList, BomBillEnum.STATUS.getAttr());
                String bomStatusStr = Objects.equals(bomStatus, 0) ? BomStatusEnum.DISABLE.getName() : BomStatusEnum.ENABLE.getName();
                JSONObject bomObj1 = ExplainUtil.getSecondTitleObj(false, BomBillEnum.STATUS.getAttrName(), bomStatusStr);
                JSONObject bomObj2 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(bomObj1);
                secondTitle.add(bomObj2);
                break;
            // 生产单
            case PRODUCTION_ORDER:
                // 状态、修改时间
                Integer prOrderStatus = getIntegerFromFormData(dataList, ProductionOrderEnum.STATUS.getAttr());
                ProductionOrderStatusEnum prOrderStatusEnum = ProductionOrderStatusEnum.getByCode(prOrderStatus);
                JSONObject productctionObj1 = ExplainUtil.getSecondTitleObj(false, ProductionOrderEnum.STATUS.getAttrName(), prOrderStatusEnum.getAlias());
                JSONObject productctionObj2 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(StringConstant.TURNOVER_TINE), updateTimeStr);
                secondTitle.add(productctionObj1);
                secondTitle.add(productctionObj2);
                break;
            case WORK_ORDER:
                WorkOrderEntity workOrderEntity = workOrderModel.getByKey(dataId, corpid);
                Integer workOrderStatus = workOrderEntity.getStatus();
                WorkOrderStatusEnum workOrderStatusEnum = WorkOrderStatusEnum.getByCode(workOrderStatus);
                WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderEntity.getTemplateId(), corpid);
                boolean isFree = workOrderTemplateEntity.getIsFree().equals(1);

                JSONObject workOrderObj1 = ExplainUtil.getSecondTitleObj(true, WorkOrderEnum.OWNER_ID.getAttrName(), managerName);
                secondTitle.add(workOrderObj1);
                if (!isFree) {
                    WorkOrderStageEntity workOrderStageEntity = workOrderStageModel.getByKey(workOrderEntity.getNowStageId(), corpid);
                    JSONObject workOrderObj2 = ExplainUtil.getSecondTitleObj(false, WorkOrderEnum.STAGE_NAME.getAttrName(), workOrderStageEntity.getName());
                    secondTitle.add(workOrderObj2);
                }
                JSONObject workOrderObj3 = ExplainUtil.getSecondTitleObj(false, WorkOrderEnum.STATUS.getAttrName(), workOrderStatusEnum.getName());
                secondTitle.add(workOrderObj3);
                break;
            default:
                break;
        }
    }

    /**
     * Description: 处理web端数据标签，摘要，标题
     *
     * @param data
     * @param businessType
     * @throws XbbException
     * @author 刘阳
     * @date 2019/6/28 2:47 PM
     * @since v1.0
     */
    public void handelDetail(Integer saasMark,Long formId,JSONObject data, Integer businessType, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt, String corpid, Long dataId, JSONArray secondTitle, JSONArray tags, PaasFormEntityExt paasFormEntityExt, List<FieldAttrEntity> explainList, DetailTitlePojo titlePojo, Integer subBusinessType, String userId) throws XbbException {
        try {
            List<PaasFormDataEntityExt> childList = new ArrayList<>();
            List<SummaryDataPoJo> summaryList;
            //跟进记录，供应商跟进记录，工作报告沿用老枚举，不走paas
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode())
                    || Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode())
                    || Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())) {
                JSONArray summaryAttrArray = mobileDetailService.getShowAttrList(businessType);
                summaryList = ExplainUtil.getSummaryDataList(summaryAttrArray, data, explainMap, paasFormDataEntityExt);
                mobileDetailService.transferKeyToShowValue(corpid, summaryList, businessType);
                mobileDetailService.handleSummarySpecialAttr(corpid, summaryList, businessType, data, dataId, paasFormDataEntityExt);
            } else {
                if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                    // 客户最后跟进时间
                    FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
                    formConfigGetDTO.setCorpid(paasFormDataEntityExt.getCorpid());
                    formConfigGetDTO.setBusinessType(businessType);
                    formConfigGetDTO.setFormId(paasFormDataEntityExt.getFormId());
                    Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
                    String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig());
                    if(Objects.equals(lastConnectTime, "0")){
                        String time = data.getString(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr());
                        long lastTime = DateTimeUtil.getInt(time, DateTimeUtil.SDFYMDHM);
                        data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), DateUtil.getString(lastTime * 1000L, DateUtil.SDFYMDHM));
                    }
                } else if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                    // 线索最后跟进时间
                    FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
                    formConfigGetDTO.setCorpid(paasFormDataEntityExt.getCorpid());
                    formConfigGetDTO.setBusinessType(businessType);
                    formConfigGetDTO.setFormId(paasFormDataEntityExt.getFormId());
                    Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
                    String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig());
                    if(Objects.equals(lastConnectTime, "0")){
                        String time = data.getString(ClueEnum.LAST_CONNECT_TIME.getAttr());
                        data.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), DateTimeUtil.getInt(time, DateTimeUtil.SDFYMDHM));
                    }
                }
                // 解析摘要
                summaryList = ExplainUtil.getSpecialSummaryList(paasFormEntityExt.getSummaryList(), data, explainMap, paasFormDataEntityExt);
                //客户公海池特殊处理 负责人->前负责人
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(data.getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()), 1)) {
                    //mobileDetailService.handelCustomerPublic(corpid, summaryList, true, dataId, businessType);
                    for(SummaryDataPoJo poJo : summaryList) {
                        if (Objects.equals(poJo.getAttr(), CustomerManagementEnum.OWNER_ID.getAttr())) {
                            poJo.setAttrName(FieldTypeEnum.PRE_OWNER_ID.getDescription());
                            break;
                        }
                    }
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(data.getInteger(ClueEnum.IS_PUBLIC.getAttr()), 1)) {
                    for(SummaryDataPoJo poJo : summaryList) {
                        if (Objects.equals(poJo.getAttr(), ClueEnum.OWNER_ID.getAttr())) {
                            poJo.setAttrName(FieldTypeEnum.PRE_OWNER_ID.getDescription());
                            break;
                        }
                    }
                }
                //访客计划延期原因，延期备注
                if (Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())) {
                    mobileDetailService.handelCommunicatePlan(corpid, data, summaryList, paasFormDataEntityExt);
                }
                childList = mobileDetailService.handleSummarySpecialAttr(corpid, summaryList, businessType, data, dataId, paasFormDataEntityExt);
                mobileDetailService.specialTransferKeyToShowValue(corpid, summaryList, businessType, data, paasFormDataEntityExt.getFormId());
            }
            // 科学计数
            String regx = "^((-?\\\\d+.?\\\\d*)[Ee]{1}(-?\\\\d+))$";
            Pattern pattern = Pattern.compile(regx);
            for (SummaryDataPoJo pojo : summaryList) {
                JSONObject commPlanObj = new JSONObject();
                List<Object> list = CollectionsUtil.isEmpty(pojo.getValue()) ? new ArrayList<>() : pojo.getValue();
                if (list.size() > 0) {
                    if (list.get(0) == null) {
                        list = new ArrayList<>();
                    }
                }
                String value = "";
                StringBuilder stringBuilder1 = new StringBuilder();
                // 科学计数
                //String regx = "^((-?\\\\d+.?\\\\d*)[Ee]{1}(-?\\\\d+))$";
                //Pattern pattern = Pattern.compile(regx);
                for (Object object1 : list) {
                    boolean isNumber = pattern.matcher(object1.toString()).matches();
                    if (isNumber) {
                        try {
                            BigDecimal b = new BigDecimal(String.valueOf(object1));
                            object1 = b.stripTrailingZeros().toPlainString();
                        } catch (Exception e) {
                            LOG.error("科学计数异常：" + object1);
                        }
                    }
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(object1.toString());
                    String s = stringBuilder.toString() + "、";
                    stringBuilder1.append(s);
                }
                value = stringBuilder1.toString();
                if (value.length() > 0) {
                    value = value.substring(0, value.length() - 1);
                }
                //应收款，付款计划，销售机会预估结束时间超时标红
                if ((Objects.equals(businessType,XbbRefTypeEnum.PAYMENT.getCode()) && Objects.equals(pojo.getAttr(), PaymentEnum.ESTIMATE_TIME.getAttr()))
                        || (Objects.equals(businessType,XbbRefTypeEnum.PAY_PLAN.getCode()) && Objects.equals(pojo.getAttr(), PayPlanEnum.ESTIMATE_TIME.getAttr()))
                        || (Objects.equals(businessType,XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) && Objects.equals(pojo.getAttr(), SalesOpportunityEnum.ESTIMATE_END_TIME.getAttr()))) {
                    if (Objects.isNull(pojo.getValue()) || (Objects.nonNull(pojo.getValue()) && pojo.getValue().isEmpty())) {
                        commPlanObj = ExplainUtil.getSecondTitleObj(false, pojo.getAttrName(), value);
                        secondTitle.add(commPlanObj);
                    } else {
                        Object object1 = pojo.getValue().get(0);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = dateFormat.parse(object1.toString());
                        dateFormat.format(date);
                        long a = date.getTime() / 1000;
                        long b = DateUtil.getTodayInt();
                        if (a < b) {
                            List<Integer> noRemindCode = Arrays.asList(StageTypeEnum.SUCCESS_STAGE.getType(),StageTypeEnum.FAIL_STAGE.getType(),StageTypeEnum.CANCEL_STAGE.getType());
                            JSONObject object = new JSONObject();
                            SaleStageEntity saleStage = null;
                            String code = data.getString(SalesOpportunityEnum.SALE_STAGE.getAttr());
                            if (StringUtil.isNotEmpty(code)) {
                                saleStage = saleStageModel.getByCode(corpid, paasFormDataEntityExt.getFormId(), code);
                            }
                            if(saleStage !=null && noRemindCode.contains(saleStage.getType())){
                                object.put("type", "black");
                            }else {
                                object.put("type", "red");
                            }
                            object.put("name", pojo.getAttrName());
                            object.put("value", object1);
                            secondTitle.add(object);
                        } else {
                            commPlanObj = ExplainUtil.getSecondTitleObj(false, pojo.getAttrName(), value);
                            secondTitle.add(commPlanObj);
                        }
                    }
                } else {
                    //负责人isTeam为true前端需要
                    if (Objects.equals(pojo.getAttrName(), WorkOrderEnum.OWNER_ID.getAttrName()) || Objects.equals(pojo.getAttrName(), WorkOrderEnum.COUSERID.getAttrName())) {
                        commPlanObj = ExplainUtil.getSecondTitleObj(true, pojo.getAttrName(), value);
                        secondTitle.add(commPlanObj);
                    } else {
                        commPlanObj = ExplainUtil.getSecondTitleObj(false, pojo.getAttrName(), value);
                        secondTitle.add(commPlanObj);
                    }
                }
            }
            //web端详情特殊摘要
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch (xbbRefTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                    String cStayTimeStr = stageAverageStayTimeHelp.getAverageStayTime(saasMark, businessType, corpid, formId, dataId, paasFormDataEntityExt.getData());
                    if (cStayTimeStr != null) {
                        JSONObject cusObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.CURRENT_STAGE_LONG), cStayTimeStr);
                        secondTitle.add(cusObj3);
                    }
                    break;
                case SALES_OPPORTUNITY:
                    String opStayTimeStr = stageAverageStayTimeHelp.getAverageStayTime(saasMark, businessType, corpid, formId, dataId, paasFormDataEntityExt.getData());
                    if (opStayTimeStr != null) {
                        JSONObject opporObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.STAY_LONG_TIME), opStayTimeStr);
                        secondTitle.add(opporObj3);
                    }
                    break;
                case PRODUCT:
                    for (int i = 0; i < secondTitle.size(); i++) {
                        JSONObject jsonObject = (JSONObject) secondTitle.get(i);
                        if (Objects.equals(jsonObject.getString("name"), ProductEnum.STOCK.getAttrName())) {
                            // 获取父产品下的子产品
                            ChildProductDTO childProductDTO = new ChildProductDTO();
                            childProductDTO.setCorpid(corpid);
                            childProductDTO.setParentProductId(Collections.singletonList(dataId));
                            PaasFormDataEsListVO esDataList = productService.getChildProductList(childProductDTO);
                            List<PaasFormDataEntityExt> childProductList = esDataList.getPaasFormDataESList();
                            List<Long> productIdIn = new ArrayList<>();
                            for (PaasFormDataEntityExt entity : childProductList) {
                                productIdIn.add(entity.getId());
                            }

                            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                            param.put(StringConstant.CORPID, corpid);
                            param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                            param.put("productIdIn", productIdIn);
                            // param.put("warehouseIdIn", warehouseIdList);
                            param.put("warehouseChecked", 1);
                            param.put("columns", "num, warehouse_id");
                            List<ProductWarehouseEntity> productWarehouseList = productWarehouseModel.findEntitysWithWarehouseChecked(param,1);

                            double stock = 0D;
                            for (ProductWarehouseEntity productWarehouseEntity : productWarehouseList) {
                                if (Objects.equals(productWarehouseEntity.getWarehouseId(), 0L)) {
                                    // 过滤全仓
                                    continue;
                                }
                                stock = Arith.add(stock, productWarehouseEntity.getNum());
                            }
                            jsonObject.put("value", stock);
                            break;
                        }
                    }
                    break;
                case CLUE:
                    String clueStayTimeStr = stageAverageStayTimeHelp.getAverageStayTime(saasMark, businessType, corpid, formId, dataId, paasFormDataEntityExt.getData());
                    if (clueStayTimeStr != null) {
                        JSONObject cusObj3 = ExplainUtil.getSecondTitleObj(false, I18nMessageUtil.getMessage(I18nStringConstant.CURRENT_STAGE_LONG), clueStayTimeStr);
                        secondTitle.add(cusObj3);
                    }
                    break;
                default:
                    break;
            }

            childList = handelCommonTags(data, businessType, explainMap, paasFormDataEntityExt, corpid, tags, paasFormEntityExt, subBusinessType, dataId, userId);
            //saas数据标题
            // 解析标题
            List<FormTitlePoJo> formTitleList = ExplainUtil.getSpecailFormTitle(JSONArray.parseArray(paasFormEntityExt.getCustomTitle()), explainMap, data, explainList, paasFormDataEntityExt);
            for (FormTitlePoJo formTitlePoJo : formTitleList) {
                if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && Objects.equals(formTitlePoJo.getAttr(), ProductEnum.COST.getAttr())) {
                    formTitlePoJo.setValue(Collections.singletonList(productService.getCostBySummary(childList, corpid, dataId)));
                } else if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && Objects.equals(formTitlePoJo.getAttr(), ProductEnum.PRICE.getAttr())) {
                    formTitlePoJo.setValue(Collections.singletonList(productService.getPriceBySummary(childList, corpid, dataId)));
                }
            }

            StringBuilder title = new StringBuilder();
            for (FormTitlePoJo item : formTitleList) {
                title.append(item.getContent());
                title.append(" ");
                for (Object object : item.getValue()) {
                    title.append(object.toString());
                    title.append(" ");
                }
            }
            titlePojo.setName(title.toString());
        } catch (XbbException e) {
            LOG.error("处理web端数据标签，摘要，标题错误", e);
        } catch (ParseException e) {
            LOG.error("时间转化失败", e);
        }
    }

    public List<PaasFormDataEntityExt> handelCommonTags(JSONObject data, Integer businessType, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt,
                                                        String corpid, JSONArray tags, PaasFormEntityExt paasFormEntityExt, Integer subBusinessType, Long dataId, String userId) throws XbbException {
        // 解析标签
        List<SummaryDataPoJo> labelsList = ExplainUtil.getSpecialSummaryList(paasFormEntityExt.getLabelsList(), data, explainMap, paasFormDataEntityExt);
        //客户公海池特殊处理 负责人->前负责人
        boolean isPublic = Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) || Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_PUBLIC.getCode());
        if (isPublic) {
            mobileDetailService.handelPublic(corpid, labelsList, dataId, businessType);
        }
        if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.ORDER.getCode())) {
            //是否包含红冲合同（即是否为退货合同）
            Integer hasRed = data.getIntValue(ContractEnum.HAS_RED.getAttr());
            if (Objects.equals(hasRed, 1)) {
                JSONObject object = new JSONObject();
                object.put("type", "red");
                object.put("value", I18nMessageUtil.getMessage(I18nStringConstant.RETURN_CONTRACT));
                tags.add(object);
            }
        }
        //访客计划延期的情况标签塞一个（访客计划状态）
        if (Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())) {
            mobileDetailService.handleCommunicatePlan(labelsList, data);
        }
        //回款计划要塞入一个回款计划状态
        if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_TASK.getCode())){
            mobileDetailService.handlePaymentTask(labelsList, data);
        }

        List<PaasFormDataEntityExt> childDataList = new ArrayList<>();
        childDataList = mobileDetailService.handleSummarySpecialAttr(corpid, labelsList, businessType, data, dataId, paasFormDataEntityExt);
        // SaaS业务特殊处理，将数据字典的key值转成显示的value值
        mobileDetailService.specialTransferKeyToShowValue(corpid, labelsList, businessType, data, paasFormDataEntityExt.getFormId());

        Map<Long, LabelPojo> nameToLabel = dealLabel(paasFormDataEntityExt, corpid, labelsList);
        for (SummaryDataPoJo pojo : labelsList) {
            JSONObject object = new JSONObject();
            List<Object> list = CollectionsUtil.isEmpty(pojo.getValue()) ? new ArrayList<>() : pojo.getValue();
            if (Objects.equals(pojo.getFieldType(), FieldTypeEnum.LABEL.getType())){

                for (Object o : list) {
                    if (o instanceof JSONObject) {
                        JSONObject object1 = new JSONObject();
                        object1.put("value", o);
                        object1.put("type", "label");
                        tags.add(object1);
                    } else {
                        Long id = Long.valueOf(String.valueOf(o));
                        if (Objects.nonNull(nameToLabel.get(id))) {
                            JSONObject object1 = new JSONObject();
                            object1.put("value", nameToLabel.get(id));
                            object1.put("type", "label");
                            tags.add(object1);
                        }
                    }
                }
                //个人标签tags展示
                PersonLabelFindDTO personLabelFindDTO = new PersonLabelFindDTO(corpid, businessType, dataId, userId);
                PersonLabelEntity personLabelEntity = personLabelService.findEntitys(personLabelFindDTO);
                if (Objects.nonNull(personLabelEntity)) {
                    JSONArray labelNameArray = personLabelEntity.getLabelName();
                    if (labelNameArray !=null && labelNameArray.size() > 0) {
                        JSONObject object1 = new JSONObject();
                        object1.put("value", personLabelEntity);
                        object1.put("type", "personLabel");
                        tags.add(object1);
                    }
                }

                continue;
            }
            String value = "";
            for (Object object1 : list) {
                value = object1.toString() + "-";
            }
            if (StringUtil.isNotEmpty(value)) {
                value = value.substring(0, value.length() - 1);
            }
            if (!Objects.equals(value, "")) {
                object.put("value", value);
                object.put("type", "normal");
                tags.add(object);
            }
        }

        return childDataList;
    }

    private Map<Long, LabelPojo> dealLabel(PaasFormDataEntityExt paasFormDataEntityExt, String corpid, List<SummaryDataPoJo> labelsList) {
        List<Object> list = new ArrayList<>();
        for (SummaryDataPoJo summaryDataPoJo : labelsList) {
            if (Objects.equals(summaryDataPoJo.getFieldType(), FieldTypeEnum.LABEL.getType())){
                list = summaryDataPoJo.getValue();
            }
        }
        return labelModel.dealLabel(paasFormDataEntityExt.getFormId(), paasFormDataEntityExt.getAppId(), corpid, list);
    }

    /**
     * 加载详情标签
     *
     * @param businessType          业务类型
     * @param tags                  标签
     * @param paasFormDataEntityExt 业务实体
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-04-17 10:40
     * @version v1.0
     * @since v1.0
     */
    public void handelDetailTags(Integer businessType, JSONArray tags, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        if (xbbRefTypeEnum == XbbRefTypeEnum.COMMUNICATE_PLAN) {
            // 访客计划状态，智能助手名称
            Integer isDelay = getIntegerFromFormData(paasFormDataEntityExt.getData(), CommunicatePlanEnum.IS_DELAY.getAttr());
            String status = FastJsonHelper.getStringFromFormData(paasFormDataEntityExt.getData(), CommunicatePlanEnum.STATUS.getAttr());
            // 访客计划延期时改状态名为已延期，不用判断状态
            // status = isDelay == 1 ? CommunicatePlanStatusEnum.DELAY.getCode() : status;
            CommunicatePlanStatusEnum statusEnum = CommunicatePlanStatusEnum.getByCode(status);
            JSONObject object = new JSONObject();
            object.put("value", statusEnum.getAlias());
            object.put("type", "normal");
            tags.add(object);

        } else if (xbbRefTypeEnum == XbbRefTypeEnum.CONTRACT) {
            Integer hasRedInt = getIntegerFromFormData(paasFormDataEntityExt.getData(), ContractEnum.HAS_RED.getAttr());
            boolean hasRed = Objects.equals(hasRedInt, 1);
            if (hasRed) {
                JSONObject object = new JSONObject();
                object.put("value", I18nMessageUtil.getMessage(I18nStringConstant.RETURN_CONTRACT));
                object.put("type", "normal");
                tags.add(object);
            }
        }
    }


    /**
     * 处理详情页关联新建
     *
     * @param businessType          业务类型
     * @param paasFormDataEntityExt 实体
     * @param workFlowPojoList      pojo数据
     * @param userVO
     * @throws XbbException 异常
     */
    public void handelDetailWorkFlow(Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, List<WorkFlowPojo> workFlowPojoList, UserVO userVO) throws XbbException {
        //原方法调用默认都为非经销商
        HandelDetailPojo handelDetailPojo = new HandelDetailPojo(null, businessType, paasFormDataEntityExt, userVO, workFlowPojoList);
        handelDetailWorkFlow(handelDetailPojo);
    }
    /**
     * 处理详情页关联新建
     * @param handelDetailPojo
     * @throws XbbException
     * @since v1.0
     * @version v1.0
     */
    public void handelDetailWorkFlow(HandelDetailPojo handelDetailPojo) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = handelDetailPojo.getPaasFormDataEntityExt();
        List<WorkFlowPojo> workFlowPojoList = handelDetailPojo.getWorkFlowPojoList();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer distributorMark = handelDetailPojo.getDistributorMark();
        Set<String> permSet = userVO.getPermSet();
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermission(businessType, permSet);
        JSONObject dataList = paasFormDataEntityExt.getData();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        String corpid = paasFormDataEntityExt.getCorpid();
        //对于应收款 回款单数据,列表中既有模式一数据,又有模式二数据,获取数据的模式
        Long modelType = paasFormDataEntityExt.getSysLong10();
        //工单应用是否开启
        Boolean workOrderEnable = false;
        //个人能用的工单模板
        List<WorkOrderFormEntity> workOrderEnableForms;
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 获取对应businessType的alias
        List<String> aliasIn = new ArrayList<>();
        for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
            if (Objects.isNull(workFlowEnum.getBusinessType())) {
                continue;
            }
            aliasIn.add(XbbRefTypeEnum.getByCode(workFlowEnum.getBusinessType()).getAlias());
        }
        param.put("corpid", corpid);
        param.put("aliasIn", aliasIn);
        param.put("del", DelEnum.NORMAL.getDel());
        // 经销商拆分菜单的需要经销商的菜单关联新建（经销商联系人等） + 非经销商的菜单关联新建（回款等）
        boolean isDistributor = XbbRefTypeEnum.isDistributorBusinessType(businessType);
        if (!isDistributor) {
            param.put("distributorMark", DistributorMarkEnum.OTHER.getCode());
        }
        List<PaasMenuEntity> paasMenuEntities = paasMenuModel.findEntitys(param);
        // 记录businessType与menuName的关系
        Map<Integer, String> paasBusinessTypeToName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Integer, PaasMenuEntity> menuMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (isDistributor) {
            paasMenuEntities.forEach(item -> {
                int code = XbbRefTypeEnum.getByAlias(item.getAlias()).getCode();
                if (!menuMap.containsKey(code) || Objects.equals(item.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    menuMap.put(code, item);
                }
            });
            menuMap.forEach((key, value) -> paasBusinessTypeToName.put(key, value.getName()));
        } else {
            paasMenuEntities.forEach(item-> paasBusinessTypeToName.put(XbbRefTypeEnum.getByAlias(item.getAlias()).getCode(),item.getName()));
        }
        param.clear();
        //
        List<Long> subIdList = new ArrayList<>();
        param.put("corpid",corpid);
        param.put("del",BasicConstant.ZERO);
        param.put("isCancel",BasicConstant.ZERO);
        double invoiceAmount = 0;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        Boolean contractOrPurchaseCanInvoice = invoiceCommonHelper.checkContractOrPurchaseInvoice(paasFormDataEntityExt,corpid,redundantTemplateTypeEnum);
        Long nowModelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
        switch (xbbRefTypeEnum) {
            case PAYMENT:
                //获取当前处于什么模式
                boolean invoiceModelFlag = fundSetHelp.checkInvoiceModelFlag(modelType, nowModelType);
                String paymentStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getCode());
                Integer isRed = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList,PaymentEnum.RECEIVABLE_IS_RED.getAttr(),BasicConstant.ONE);
                boolean isRedReceivables = Objects.equals(paymentStatus,PaymentStatusEnum.RED_RECEIVABLES.getCode()) && Objects.equals(isRed,BasicConstant.ONE);
                param.put("paymentId",paasFormDataEntityExt.getId());
                List<InvoiceRelationshipEntity> invoiceRelationshipEntities = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntities)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntities) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                Double paymentAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, PaymentEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                Double unAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList,PaymentEnum.UN_AMOUNT.getAttr(),BasicConstant.ZERO_DOUBLE);
                Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, PaymentEnum.CUSTOMER.getAttr(), 0L);
                PaymentBalanceEntity paymentBalanceEntity = paymentBalanceModel.getByCustomerId(customerId, corpid);
                //判断该客户下是否存在预收款余额 且 大于0
                boolean isBalanceAmountExist = false;
                if(paymentBalanceEntity != null && paymentBalanceEntity.getAdvancePaymentBalance() > 0){
                    isBalanceAmountExist = true;
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    boolean notItemSheet = !(Objects.equals(paymentStatus, PaymentStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(paymentStatus, PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())) && Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_PAYMENT_SHEET);
                    if (notItemSheet) {
                        continue;
                    }
                    //判断是否为 已收款/坏账/部分坏账状态
                    boolean noWriteOffPrePayment = Objects.equals(paymentStatus, PaymentStatusEnum.RECEIVABLES.getCode()) || Objects.equals(paymentStatus, PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode()) || Objects.equals(paymentStatus, PaymentStatusEnum.BAD_DEBT.getCode());
                    if(!isBalanceAmountExist || noWriteOffPrePayment){
                        if(Objects.equals(workFlowEnum, WorkFlowEnum.WRITE_OFF_PREPAYMENT)){
                            continue;
                        }
                    }
                    if((isRedReceivables || unAmount <= 0) && !(Objects.equals(workFlowEnum,WorkFlowEnum.PAYMENT_INVOICE))){
                        continue;
                        /*if(Objects.equals(workFlowEnum,WorkFlowEnum.PAYMENT_BAD)){
                            continue;
                        }*/
                    }
                    List<String> invoiceStatus = new ArrayList<>();
                    invoiceStatus.add(PaymentStatusEnum.UN_RECEIVABLES.getCode());
                    invoiceStatus.add(PaymentStatusEnum.PARTIAL_RECEIPTS.getCode());
                    invoiceStatus.add(PaymentStatusEnum.RECEIVABLES.getCode());
                    //可以进行开票
                    boolean notItemInvoice = invoiceAmount < paymentAmount && invoiceStatus.contains(paymentStatus) && contractOrPurchaseCanInvoice;
                    //非模式二并且满足能开票的前提可以进行开票
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.PAYMENT_INVOICE)) {
                        if (!notItemInvoice || invoiceModelFlag) {
                            continue;
                        }
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojo.setDistributorMark(distributorMark);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case PAY_PLAN:
                String payStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());
                //Double inputInvoiceAmount = saasUpdateHelp.getDoubleOrDefaultFromFormData(dataList, PayPlanEnum.INVOICE_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                param.put("payPlanId",paasFormDataEntityExt.getId());
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntities = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntities)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntities) {
                        invoiceAmount = Arith.add(invoiceAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                Double payPlanAmount = getDoubleOrDefaultFromFormData(dataList, PayPlanEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                Long supplierId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, PayPlanEnum.LINK_SUPPLIER.getAttr(), 0L);
                PayBalanceEntity payBalanceEntity = payBalanceModel.getBySupplierId(supplierId, corpid);
                //判断该客户下是否存在预收款余额 且 大于0
                boolean isPayBalanceAmountExist = false;
                if(payBalanceEntity != null && payBalanceEntity.getAdvancePayBalance() > 0){
                    isPayBalanceAmountExist = true;
                }

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    boolean notItemSheet = !(Objects.equals(payStatus, PayPlanStatusEnum.UN_RECEIVABLES.getCode()) || Objects.equals(payStatus, PayPlanStatusEnum.PARTIAL_RECEIPTS.getCode())) && Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_ADD_SHEET);
                    if (notItemSheet) {
                        continue;
                    }
                    //判断是否为 已收款/坏账/部分坏账状态
                    boolean noWriteOffPrePayment = Objects.equals(payStatus, PayPlanStatusEnum.RECEIVABLES.getCode()) || Objects.equals(payStatus, PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode()) || Objects.equals(payStatus, PayPlanStatusEnum.BAD_DEBT.getCode());
                    if(!isPayBalanceAmountExist || noWriteOffPrePayment){
                        if(Objects.equals(workFlowEnum, WorkFlowEnum.WRITE_OFF_PREPAY)){
                            continue;
                        }
                    }
                    List<String> invoiceStatus = new ArrayList<>();
                    invoiceStatus.add(PayPlanStatusEnum.UN_RECEIVABLES.getCode());
                    invoiceStatus.add(PayPlanStatusEnum.PARTIAL_RECEIPTS.getCode());
                    invoiceStatus.add(PayPlanStatusEnum.RECEIVABLES.getCode());
                    boolean notItemInputInvoice = invoiceAmount < payPlanAmount && invoiceStatus.contains(payStatus) && contractOrPurchaseCanInvoice;
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.PAY_PLAN_PURCHASE_INVOICE) && !notItemInputInvoice) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case PAYMENT_SHEET:
                //获取当前处于什么模式
                invoiceModelFlag = fundSetHelp.checkInvoiceModelFlag(modelType, nowModelType);
                Double paymentSheetAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, PaymentSheetEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                //回款单类型
                String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.WRITE_OFF.getCode());
                List<PaasFormDataEntityExt> paasFormDataEntityExtList = fundHelp.getChildEsDataListByParentUuid(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET,corpid,paasFormDataEntityExt.getUuid(),null);
                if(!Objects.equals(paasFormDataEntityExt.getAlone(), SheetAloneEnum.NORMAL.getCode())) {
                    if (CollectionsUtil.isNotEmpty(paasFormDataEntityExtList)) {
                        for (PaasFormDataEntityExt paasFormData : paasFormDataEntityExtList) {
                            subIdList.add(paasFormData.getId());
                        }
                    }
                }else {
                    subIdList.add(paasFormDataEntityExt.getId());
                }
                param.put("paymentSheetIdIn",subIdList);
                List<InvoiceRelationshipEntity> invoiceRelationship = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(invoiceRelationship)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationship) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                //还要判断登录人员是不是有“新建进项发票”的权限 FIX 2020/5/13 wangtengwei
                boolean invoiceFlow = invoiceAmount < paymentSheetAmount && SheetTypeEnum.ifNewInvoice(paymentSheetType) && userVO.getPermSet().contains(ProPermissionAliasEnum.INVOICE_ADD.getAlias()) && contractOrPurchaseCanInvoice;
                //boolean invoiceFlow = checkWorkFlowAddInvoice4PaymentSheet(paymentSheetType, dataList);
                //开票模式，回款单详情也不能有新建发票按钮（开票模式时基于发票产生应收，再生成回款单）
                if (invoiceFlow && !invoiceModelFlag) {
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(WorkFlowEnum.PAYMENT_SHEET_INVOICE, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojo.setDistributorMark(distributorMark);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case PAY_SHEET:
                //付款单类型
                Double paySheetAmount = getDoubleOrDefaultFromFormData(dataList, PaySheetEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                List<PaasFormDataEntityExt> paasFormDataExtList = fundHelp.getChildEsDataListByParentUuid(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET,corpid,paasFormDataEntityExt.getUuid(),null);
                if(!Objects.equals(paasFormDataEntityExt.getAlone(), SheetAloneEnum.NORMAL.getCode())) {
                    if (CollectionsUtil.isNotEmpty(paasFormDataExtList)) {
                        for (PaasFormDataEntityExt paasFormData : paasFormDataExtList) {
                            subIdList.add(paasFormData.getId());
                        }
                    }
                }else {
                    subIdList.add(paasFormDataEntityExt.getId());
                }
                param.put("paySheetIdIn",subIdList);
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationship = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationship)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationship) {
                        invoiceAmount = Arith.add(invoiceAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                //还要判断登录人员是不是有“新建进项发票”的权限 FIX 2020/5/13 wangtengwei
                boolean purchaseInvoiceFlow = invoiceAmount < paySheetAmount && SheetTypeEnum.ifNewInvoice(paySheetType) && userVO.getPermSet().contains(ProPermissionAliasEnum.PURCHASE_INVOICE_ADD.getAlias()) && contractOrPurchaseCanInvoice;
                //invoiceFlow = checkWorkFlowAddInvoice4PaySheet(paySheetType, dataList);
                if (purchaseInvoiceFlow) {
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(WorkFlowEnum.PAY_SHEET_INVOICE, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case PRODUCTION_ORDER:
                Integer status = getIntegerOrDefaultFromFormData(dataList, ProductionOrderEnum.STATUS.getAttr(), BasicConstant.ZERO);
                // 获取成品未入库数量
                Double alreadyUnInstockNum = getDoubleOrDefaultFromFormData(dataList, ProductionOrderEnum.PRODUCT_UNINSTOCK_NUM.getAttr(), 0.0D);
                ProductionOrderEntityExt productionOrderEntityExt = new ProductionOrderEntityExt();
                BeanUtil.copyProperties(paasFormDataEntityExt, productionOrderEntityExt);
                boolean hasReturnedInstock = productionOrderService.hasReturnedMaterielInstock(productionOrderEntityExt);
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(ProductionOrderStatusEnum.UNFINISHED.getCode(), status)) {
                        if (!hasReturnedInstock && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)) {
                            continue;
                        }
                    } else if (Objects.equals(ProductionOrderStatusEnum.CLOSED.getCode(), status)) {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_OUTSTOCK)) {
                            continue;
                        }
                        if (!hasReturnedInstock && Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_OUTSTOCK)
                                || Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_MATERIEL_INSTOCK)
                                || Objects.equals(workFlowEnum, WorkFlowEnum.PRODUCTION_ORDER_PRODUCT_INSTOCK)) {
                            continue;
                        }
                    }

                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case INVENTORY:
                Integer inventoryInstockId = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.INSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer isProfit = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.IF_PROFIT.getAttr(), BasicConstant.ZERO);
                Integer inventoryOutstockId = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.OUTSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer isLoss = getIntegerOrDefaultFromFormData(dataList, InventoryEnum.IF_LOSS.getAttr(), BasicConstant.ZERO);

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    // 盘点单没有盘盈或者已经生成过入库单 则不显示‘生成入库单’按钮
                    boolean noInstock = (Objects.equals(isProfit, 0) || inventoryInstockId > 0) && Objects.equals(workFlowEnum, WorkFlowEnum.INVENTORY_INSTOCK);
                    if (noInstock) {
                        continue;
                    }
                    // 盘点单没有盘亏或者已经生成过出库单 则不显示‘生成出库单’按钮
                    boolean noOutstock = (Objects.equals(isLoss, 0) || inventoryOutstockId > 0) && Objects.equals(workFlowEnum, WorkFlowEnum.INVENTORY_OUTSTOCK);
                    if (noOutstock) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }

                break;
            case PURCHASE:
                Integer isAllInComing = getIntegerOrDefaultFromFormData(dataList, PurchaseEnum.ALL_INCOMING.getAttr(), BasicConstant.ZERO);
                String receiveStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PurchaseEnum.RECEIVE_STATUS.getAttr(), ReceiveStatusEnum.UNRECEIVED.getCode());
                JSONArray instockArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(dataList, PurchaseEnum.INSTOCK_ID.getAttr(), new JSONArray());
                Double purchaseAmount = getDoubleOrDefaultFromFormData(dataList, PurchaseEnum.TOTAL_MONEY.getAttr(), BasicConstant.ZERO_DOUBLE);
                param.put("purchaseId",paasFormDataEntityExt.getId());
                List<PurchaseInvoiceRelationshipEntity> purchaseInvoiceRelationshipEntityList = purchaseInvoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(purchaseInvoiceRelationshipEntityList)){
                    for(PurchaseInvoiceRelationshipEntity purchaseInvoiceRelationshipEntity : purchaseInvoiceRelationshipEntityList) {
                        invoiceAmount = Arith.add(invoiceAmount, purchaseInvoiceRelationshipEntity.getMoney());
                    }
                }
                Long returnedPurchaseId = FastJsonHelper.getLongOrDefaultFromFormData(dataList, PurchaseEnum.RETURNED_PURCHASE_ID.getAttr(), 0L);
                boolean notItemReturnPurchase = instockArr.isEmpty() || returnedPurchaseId > 0;
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {

                    if (esignHelp.addEsignWorkFlow(permSet, workFlowPojoList, workFlowEnum,
                            xbbRefTypeEnum, paasFormDataEntityExt)) {
                        continue;
                    }

                    if (Objects.equals(isAllInComing, BasicConstant.ONE) && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(receiveStatus, ReceiveStatusEnum.CLOSED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INSTOCK)) {
                        continue;
                    }
                    if (notItemReturnPurchase && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_RETURNED)) {
                        continue;
                    }
                    if (invoiceAmount >= purchaseAmount && Objects.equals(workFlowEnum, WorkFlowEnum.PURCHASE_INVOICE)) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case CUSTOMER_MANAGEMENT:
                Integer isPublic = getIntegerOrDefaultFromFormData(dataList, CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                Integer del = paasFormDataEntityExt.getDel();
                //工单未开，以及没有可以用的工单模板，移除关联新建工单
                workOrderEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                workOrderEnableForms = workOrderFormService.getTemplateWithPermission(userVO, null, null);
                if (!workOrderEnable || (Objects.nonNull(workOrderEnableForms) && workOrderEnableForms.isEmpty())) {
                    workFlowEnumList.remove(WorkFlowEnum.CUSTOMER_WORK_ORDER);
                }

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(isPublic, BasicConstant.ONE) || Objects.equals(del, DelEnum.DELETE.getDel())) {
                        continue;
                    }
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.CUSTOMER_PAYMENT) && !Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode())) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojo.setDistributorMark(distributorMark);
                    workFlowPojoList.add(workFlowPojo);
                }

                break;
            case CLUE:
                Integer publicFlag = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                String clusStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ClueEnum.CLUE_STATUS.getAttr(), "");
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(publicFlag, BasicConstant.ONE) || Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel())) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.CLUE_TRANSFORM)) {
                        if (Objects.equals(clusStatus, ClueStatusEnum.TRANSFORMED.getCode()) || Objects.equals(clusStatus, ClueStatusEnum.INVALID.getCode())) {
                            continue;
                        }
                        // 不需要改名字
                        workFlowPojoList.add(workFlowPojo);
                        continue;
                    }
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }

                break;
            case CONTRACT:
                Integer isAllComing = getIntegerOrDefaultFromFormData(dataList, ContractEnum.ALL_OUT_BOUND.getAttr(), BasicConstant.ZERO);
                String isShipped = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ContractEnum.SHIP_STATUS.getAttr(), ShipStatusEnum.UNSHIPPED.getCode());
                Double amount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, ContractEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                Double unFinishAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, ContractEnum.UN_FINISH_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                param.put("contractId",paasFormDataEntityExt.getId());
                List<InvoiceRelationshipEntity> invoiceRelationshipEntityList = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(invoiceRelationshipEntityList)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : invoiceRelationshipEntityList) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                List<ContractProductEntity> contractProductEntityList = contractProductModel.getContractProductByContractIdIn(corpid, 0, Collections.singletonList(paasFormDataEntityExt.getId()));
                boolean notNeedPurchase = contractProductEntityList.isEmpty();
                //工单未开，以及没有可以用的工单模板，移除关联新建工单
                workOrderEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                workOrderEnableForms = workOrderFormService.getTemplateWithPermission(userVO, null, null);
                if (!workOrderEnable || (Objects.nonNull(workOrderEnableForms) && workOrderEnableForms.isEmpty())) {
                    workFlowEnumList.remove(WorkFlowEnum.CONTRACT_WORK_ORDER);
                }

                // 查询是否可以超发出库
                FormConfigEntity overOutstockConfig = formConfigModel.getEntityByFormId(corpid, paasFormDataEntityExt.getFormId(), FormConfigEnum.CONTRACT_ALLOW_OUTSTOCK_PRODUCT_NUM_LARGER_SOLD.getConfig());
                boolean overOutstock = Objects.nonNull(overOutstockConfig) && Objects.equals(overOutstockConfig.getConfigValue(), "1");

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(isAllComing, BasicConstant.ONE) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_OUTSTOCK) && !overOutstock) {
                        continue;
                    }
                    if ((Objects.equals(isShipped, ShipStatusEnum.CLOSED.getCode())&& Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_OUTSTOCK))) {
                        continue;
                    }

                    if (esignHelp.addEsignWorkFlow(permSet, workFlowPojoList, workFlowEnum,
                            xbbRefTypeEnum, paasFormDataEntityExt)) {
                        continue;
                    }

                    if (invoiceAmount >= amount && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_INVOICE)) {
                        continue;
                    }
                    if (notNeedPurchase && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PURCHASE)) {
                        continue;
                    }
                    if (unFinishAmount <= BasicConstant.ZERO_DOUBLE && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PAYMENT)) {
                        continue;
                    }
                    if (!Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.CONTRACT_PAYMENT)) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
                    workFlowPojoList.add(workFlowPojo);
                }

                break;
            case RETURNED_PURCHASE:
                // 采购退货单已经生成过出库单 则不显示‘生成出库单’按钮
                Integer outstockId = getIntegerOrDefaultFromFormData(dataList, ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr(), BasicConstant.ZERO);
                String returnedStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ReturnedPurchaseEnum.RETURNED_STATUS.getAttr(), ReturnedStatusEnum.UNRETURNED.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (outstockId > 0 && Objects.equals(workFlowEnum, WorkFlowEnum.RETURNED_PURCHASE_OUTSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(returnedStatus,ReturnedStatusEnum.CLOSED.getCode()) && Objects.equals(workFlowEnum, WorkFlowEnum.RETURNED_PURCHASE_OUTSTOCK)) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }

                break;
            case TRANSFER:
                // 调拨单已经生成过出库单 则不显示‘生成出库单’按钮
                Integer transferOutstockId = getIntegerOrDefaultFromFormData(dataList, TransferEnum.OUTSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer transferInstockId = getIntegerOrDefaultFromFormData(dataList, TransferEnum.INSTOCK_ID.getAttr(), BasicConstant.ZERO);
                Integer allBound = getIntegerFromFormData(dataList, TransferEnum.ALL_IN_BOUND.getAttr());
                String transferStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, TransferEnum.TRANSFER_STATUS.getAttr(), TransferNewStatusEnum.UNTRANSFORMED.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (transferOutstockId > 0 && Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_OUTSTOCK)) {
                        continue;
                    }
                    if (Objects.equals(transferStatus, TransferNewStatusEnum.CLOSED.getCode()) && (Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_OUTSTOCK)||Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_INSTOCK))) {
                        continue;
                    }

                    // 调拨单没有生成过出库单或者全部入库完毕 则不显示‘生成入库单’按钮
                    // 老数据出入库完毕也没有标识
                    boolean isOldInAllBound = transferInstockId > 0 && transferOutstockId > 0 && Objects.isNull(allBound);
                    boolean noTransferInstock = (Objects.equals(transferOutstockId, 0) || (Objects.nonNull(allBound) && allBound > 0) || isOldInAllBound) && Objects.equals(workFlowEnum, WorkFlowEnum.TRANSFER_INSTOCK);
                    if (noTransferInstock) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case REFUND:
                if (Objects.isNull(dataList)) {
                    break;
                }
                String refundStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, RefundEnum.REFUND_STATUS.getAttr(), RefundStatusEnum.UNREFUND.getCode());
                Integer allInStock = getIntegerOrDefaultFromFormData(dataList, RefundEnum.ALL_IN_BOUND.getAttr(), BasicConstant.ONE);
                // 只有0:部分(未)入库时才展示按钮
                boolean isInStock = Objects.equals(allInStock, BasicConstant.ONE) || Objects.equals(allInStock, BasicConstant.TWO);
                boolean isClosed = Objects.equals(refundStatus, RefundStatusEnum.CLOSED.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (isInStock && Objects.equals(workFlowEnum, WorkFlowEnum.REFUND_INSTOCK)) {
                        continue;
                    }
                    if (isClosed && Objects.equals(workFlowEnum,WorkFlowEnum.REFUND_INSTOCK)) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case WORK_ORDER:
                Long workOrderId = paasFormDataEntityExt.getId();
                WorkOrderEntity workOrderEntity = workOrderModel.getByKey(workOrderId, corpid);
                if (Objects.isNull(workOrderEntity) || Objects.equals(workOrderEntity.getDel(), DelEnum.DELETE.getDel())) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                Integer workOrderStatus = workOrderEntity.getStatus();
                WorkOrderStatusEnum workOrderStatusEnum = WorkOrderStatusEnum.getByCode(workOrderStatus);

                List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntities = workOrderFlowNodeModel.getNode(workOrderId, 1, corpid);
                WorkOrderFlowNodeEntity workOrderFlowNodeEntity = workOrderFlowNodeEntities.get(0);
                WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderEntity.getTemplateId(), corpid);
                boolean isFirst = false;
                Long sourceId = workOrderFlowNodeEntity.getSourceId();
                Integer sort = workOrderFlowNodeEntity.getSort();
                //如果回退原id不等于0，即说明当前节点是回退后生成的，需要查找原节点位置
                if (sourceId != 0) {
                    WorkOrderFlowNodeEntity sourceNode = workOrderFlowNodeModel.getByKey(sourceId, corpid);
                    sort = sourceNode.getSort();
                }
                List<String> accepteUserIds = new ArrayList<>();
                if (workOrderTemplateEntity.getIsFree().equals(1)) {
                    //自由流程
                    isFirst = sort.equals(0);
                    accepteUserIds.add(workOrderFlowNodeEntity.getUserId());
                } else {
                    //指定流程
                    WorkOrderStageEntity workOrderStageEntity = workOrderStageModel.getByKey(workOrderEntity.getNowStageId(), corpid);
                    if (Objects.nonNull(workOrderStageEntity)) {
                        isFirst = sort.equals(0) && workOrderStageEntity.getSort().equals(0);
                        WorkOrderStageRuleEnum workOrderStageRuleEnum = WorkOrderStageRuleEnum.getByCode(workOrderStageEntity.getRuleId());
                        WorkOrderStageRobTypeEnum workOrderStageRobTypeEnum = WorkOrderStageRobTypeEnum.getByCode(workOrderStageEntity.getRefRobType());
                        switch (workOrderStageRuleEnum) {
                            case ROB:
                                switch (workOrderStageRobTypeEnum) {
                                    case USER:
                                        break;
                                    case SERVICE:
                                        accepteUserIds.addAll(workOrderBasicService.getServiceUserIdList(corpid, workOrderStageEntity.getRefRobId()));
                                        break;
                                    case DEPARTMENT:
                                        accepteUserIds.addAll(workOrderBasicService.getDepartmentUserIdList(corpid, workOrderStageEntity.getRefRobId()));
                                        break;
                                    default:
                                        break;
                                }
                                break;
                            default:
                                accepteUserIds.add(workOrderFlowNodeEntity.getUserId());
                                break;
                        }
                    }
                }
                Integer nodeStatus = workOrderFlowNodeEntity.getStatus();
                WorkOrderNodeStatusEnum workOrderNodeStatusEnum = WorkOrderNodeStatusEnum.getByCode(nodeStatus);

                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(userVO, userEntity);
                //老板、超管等最高权限人员
                boolean isBoss = userVO.isAdminOrBoss();

                Set<RoleSimpleVO> roleSet = userVO.getRoleSet();

                //工单主管
                boolean isWorkOrderManager = false;
                for (RoleSimpleVO roleSimpleVO : roleSet) {
                    if (Objects.equals(roleSimpleVO.getId(), RoleEnum.WORKORDER_MANAGER.getCode())) {
                        isWorkOrderManager = true;
                        break;
                    }
                }
                //负责人
                boolean isMain = false;
                //协同人
                boolean isCoop = false;
                //抄送人
                boolean isCc = false;
                //创建人
                boolean isCreator = Objects.equals(userEntity.getUserId(), workOrderEntity.getCreatorId());

                List<WorkOrderFlowUserEntity> teamUserList = workOrderFlowUserService.getTeamUserList(workOrderId, corpid);
                for (WorkOrderFlowUserEntity flowUserEntity : teamUserList) {
                    if (Objects.equals(flowUserEntity.getUserId(), userEntity.getUserId())) {
                        if (Objects.equals(flowUserEntity.getIsMain(), 1)) {
                            isMain = true;
                        }
                        if (Objects.equals(flowUserEntity.getIsMain(), 0)) {
                            isCoop = true;
                        }
                        break;
                    }
                }
                List<String> ccUserIds = workOrderCcModel.getUserIds(corpid, workOrderId);
                if (ccUserIds.contains(userVO.getUserId())) {
                    isCc = true;
                }

                //根据工单节点状态赋默认全部操作权限
                LinkedList<WorkFlowEnum> workFlowEnums = new LinkedList<>();
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    switch (workOrderNodeStatusEnum) {
                        case UNACCEPTED:
                        case TRANSFERRED:
                            if (workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_TRANSFER) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_COMPLETE) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_RESTART) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ROLLBACK)) {
                                continue;
                            }
                            break;
                        case ROLLBACK:
                        case RESTART:
                        case ONGOING:
                            if (workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ACCEPTED) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_RESTART)) {
                                continue;
                            }
                            if (workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ROLLBACK)) {
                                if (isFirst) {
                                    continue;
                                }
                            }
                            break;
                        case FINISH:
                            if (workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ACCEPTED) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_TRANSFER) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_COMPLETE) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_CLOSE) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ROLLBACK)) {
                                continue;
                            }
                            break;
                        case CLOSE:
                            if (workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ACCEPTED) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_TRANSFER) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_COMPLETE) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_CLOSE) || workFlowEnum.equals(WorkFlowEnum.WORK_ORDER_ROLLBACK)) {
                                continue;
                            }
                            break;
                        case UNKNOWN:
                            break;
                        default:
                            break;
                    }
                    workFlowEnums.add(workFlowEnum);
                }
                if (isCc && !(isMain || isBoss || isWorkOrderManager || accepteUserIds.contains(userVO.getUserId()))) {
                    //抄送人只能看，所有流转操作都没
                    workFlowEnums.removeAll(Arrays.asList(WorkFlowEnum.WORK_ORDER_ACCEPTED, WorkFlowEnum.WORK_ORDER_COMPLETE, WorkFlowEnum.WORK_ORDER_TRANSFER, WorkFlowEnum.WORK_ORDER_CLOSE, WorkFlowEnum.WORK_ORDER_RESTART, WorkFlowEnum.WORK_ORDER_ROLLBACK));
                } else {
                    //根据权限移除无权限的按钮
                    //接收,完成,转派,  工单负责人、老板、超管等最高权限人员，工单主管。
                    //接收还有抢单的人
                    if (!StringUtil.isEmpty(workOrderFlowNodeEntity.getUserId())) {
                        if (!(isBoss || isWorkOrderManager)) {
                            if (!Objects.equals(workOrderFlowNodeEntity.getUserId(), userVO.getUserId())) {
                                workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_ACCEPTED);
                            }
                        }
                    } else {
                        if (Objects.equals(workOrderFlowNodeEntity.getNodeType(), WorkOrderFlowNodeTypeEnum.ROB_NODE.getCode())) {
                            if (!(isBoss || isWorkOrderManager || accepteUserIds.contains(userVO.getUserId()))) {
                                workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_ACCEPTED);
                            }
                        } else {
                            if (!(isMain || isBoss || isWorkOrderManager || accepteUserIds.contains(userVO.getUserId()))) {
                                workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_ACCEPTED);
                            }
                        }
                    }
                    if (!(isMain || isBoss || isWorkOrderManager)) {
                        workFlowEnums.removeAll(Arrays.asList(WorkFlowEnum.WORK_ORDER_COMPLETE, WorkFlowEnum.WORK_ORDER_TRANSFER));
                    }
                    // 关闭, 非协同人（只要不是协同人，都可以），老板、超管等最高权限人员，工单主管。
                    //抢单工单-关闭  	 主负责人，老板、超管等最高权限人员，工单主管。
                    if (Objects.equals(workOrderEntity.getType(), WorkOrderTypeEnum.ROB.getCode())) {
                        if (!(isMain || isBoss || isWorkOrderManager)) {
                            workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_CLOSE);
                        }
                    } else {
                        if (isCoop && !isBoss && !isWorkOrderManager) {
                            workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_CLOSE);
                        } else if (isCc && !isMain && !isBoss && !isWorkOrderManager) {
                            workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_CLOSE);
                        } else if (!(isMain || isCoop || isBoss || isWorkOrderManager)) {
                            workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_CLOSE);
                        }
                    }
                    // 重启,	创建人，老板、超管等最高权限人员，工单主管。
                    if (!(isCreator || isBoss || isWorkOrderManager)) {
                        workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_RESTART);
                    }
                    // 回退, 	 主负责人，老板、超管等最高权限人员，工单主管。
                    if (!(isMain || isBoss || isWorkOrderManager)) {
                        workFlowEnums.remove(WorkFlowEnum.WORK_ORDER_ROLLBACK);
                    }
                }

                // 过滤掉全部出库和无关联产品的情况
                Integer shippedFlag = getIntegerOrDefaultFromFormData(dataList, WorkOrderEnum.SHIP_STATUS.getAttr(), WorkOrderShipStatusEnum.EMPTY.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnums) {
                    if ((Objects.equals(shippedFlag, WorkOrderShipStatusEnum.SHIPPED.getCode()) || Objects.equals(shippedFlag, WorkOrderShipStatusEnum.EMPTY.getCode()))
                            && Objects.equals(workFlowEnum, WorkFlowEnum.WORK_ORDER_OUTSTOCK)) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }

                break;
            case SALES_OPPORTUNITY:
                //工单未开，以及没有可以用的工单模板，移除关联新建工单
                workOrderEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                workOrderEnableForms = workOrderFormService.getTemplateWithPermission(userVO, null, null);
                Integer feeType = packageHelp.getFeeType(corpid);
                if (!Objects.equals(PackageTypeEnum.ULTIMATE.getType(), feeType)) {
                    workFlowEnumList.remove(WorkFlowEnum.OPPORTUNITY_LINK_COMPETITOR);
                }

                if (!workOrderEnable || (Objects.nonNull(workOrderEnableForms) && workOrderEnableForms.isEmpty())) {
                    workFlowEnumList.remove(WorkFlowEnum.OPPORTUNITY_WORK_ORDER);
                }
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojo.setDistributorMark(distributorMark);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case QUOTATION:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {

                    if (esignHelp.addEsignWorkFlow(permSet, workFlowPojoList, workFlowEnum,
                            xbbRefTypeEnum, paasFormDataEntityExt)) {
                        continue;
                    }

                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojo.setDistributorMark(distributorMark);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case CREDIT_LIMIT:
                String creditStatus = dataList.getString(CreditLimitEnum.STATUS.getAttr());
                if (Objects.equals(creditStatus, CreditLimitStatusEnum.NORMAL.getCode())) {
                    for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                        WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                        BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                        changeValue(paasBusinessTypeToName, workFlowPojo);
                        workFlowPojoList.add(workFlowPojo);
                    }
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(workFlowEnum, WorkFlowEnum.DISTRIBUTOR_PAYMENT) && !Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode())) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    workFlowPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case ORDER:
                //是否出库完毕
                Integer isOrderAllComing = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, OrderEnum.ALL_OUT_BOUND.getAttr(), BasicConstant.ZERO);
                //出库状态
                String isOrderShipped = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OrderEnum.SHIP_STATUS.getAttr(), ShipStatusEnum.UNSHIPPED.getCode());
                //订单金额
                Double orderAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, OrderEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                Double unOrderFinishAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, OrderEnum.UN_FINISH_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
                //订单状态
                Integer orderStatus = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, OrderEnum.STATUS.getAttr(), BasicConstant.ONE);

                param.put("contractId",paasFormDataEntityExt.getId());
                List<InvoiceRelationshipEntity> orderInvoiceRelationshipEntityList = invoiceRelationshipModel.findEntitys(param);
                if(CollectionsUtil.isNotEmpty(orderInvoiceRelationshipEntityList)){
                    for(InvoiceRelationshipEntity invoiceRelationshipEntity : orderInvoiceRelationshipEntityList) {
                        invoiceAmount = Arith.add(invoiceAmount, invoiceRelationshipEntity.getMoney());
                    }
                }
                List<ContractProductEntity> orderProductEntityList = contractProductModel.getContractProductByContractIdIn(corpid, 0, Collections.singletonList(paasFormDataEntityExt.getId()));
                boolean orderNotNeedPurchase = orderProductEntityList.isEmpty();
                //工单未开，以及没有可以用的工单模板，移除关联新建工单
                workOrderEnable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.WORK_ORDER.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                workOrderEnableForms = workOrderFormService.getTemplateWithPermission(userVO, null, null);
                if (!workOrderEnable || (Objects.nonNull(workOrderEnableForms) && workOrderEnableForms.isEmpty())) {
                    workFlowEnumList.remove(WorkFlowEnum.ORDER_WORK_ORDER);
                }

                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    //订单状态为待订单审核 待财务审核
                    if(Objects.equals(orderStatus, BasicConstant.ONE) || Objects.equals(orderStatus,BasicConstant.TWO) || Objects.equals(orderStatus,BasicConstant.SIX)){
                        continue;
                    }
                    //订单状态为待收货 已完成
                    if (Objects.equals(orderStatus,BasicConstant.FOUR) || Objects.equals(orderStatus,BasicConstant.FIVE)){
                        if (Objects.equals(workFlowEnum,workFlowEnum.ORDER_ORDER_OUTSTOCK)){
                            continue;
                        }
                    }
                    //订单状态为已关闭
                    if (Objects.equals(orderStatus,BasicConstant.SEVEN)){
                        if (Objects.equals(workFlowEnum,workFlowEnum.ORDER_ORDER_OUTSTOCK) || Objects.equals(workFlowEnum,workFlowEnum.ORDER_PURCHASE)){
                            continue;
                        }
                    }
                    if (Objects.equals(isOrderAllComing, BasicConstant.ONE) && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_ORDER_OUTSTOCK)) {
                        continue;
                    }
                    if ((Objects.equals(isOrderShipped, ShipStatusEnum.CLOSED.getCode())&& Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_ORDER_OUTSTOCK))) {
                        continue;
                    }

                    if (esignHelp.addEsignWorkFlow(permSet, workFlowPojoList, workFlowEnum,
                            xbbRefTypeEnum, paasFormDataEntityExt)) {
                        continue;
                    }

                    if (invoiceAmount >= orderAmount && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_INVOICE)) {
                        continue;
                    }
                    if (orderNotNeedPurchase && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_PURCHASE)) {
                        continue;
                    }
                    if (unOrderFinishAmount <= BasicConstant.ZERO_DOUBLE && Objects.equals(workFlowEnum, WorkFlowEnum.ORDER_PAYMENT)) {
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    if (Objects.equals(workFlowEnum,WorkFlowEnum.ORDER_PURCHASE) || Objects.equals(workFlowEnum,WorkFlowEnum.ORDER_WORK_ORDER)){
                        workFlowPojo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
                    }else {
                        workFlowPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    }
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                //订单状态为已作废 清空所有workfolw
                if (Objects.equals(orderStatus,BasicConstant.SIX)){
                    workFlowEnumList.clear();
                }
                break;
            case ORDER_OUTSTOCK:
                //出库发货单发货状态
                String expressStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OrderOutStockEnum.EXPRESS_STATUS.getAttr(), OrderOutStockExpressStatusEnum.TO_BE_DELIVERED.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.TO_BE_DELIVERED.getCode()) && Objects.equals(workFlowEnum,WorkFlowEnum.CANCELL_DELIVERY)){
                        continue;
                    }
                    if(Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.RECEIVED.getCode()) && (Objects.equals(workFlowEnum,WorkFlowEnum.NORMAL_DELIVERY) || Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_DELIVERY) || Objects.equals(workFlowEnum,WorkFlowEnum.CANCELL_DELIVERY))){
                        continue;
                    }
                    if (Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.TO_BE_RECEIVED.getCode()) && (Objects.equals(workFlowEnum,WorkFlowEnum.NORMAL_DELIVERY) || Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_DELIVERY))){
                        continue;
                    }
                    if (Objects.equals(workFlowEnum,WorkFlowEnum.ELECTRONIC_ORDER_DELIVERY)){
                        //如果电子面单应用关闭
                        // 获取公司级配置
                        CompanyConfigEntity configEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ELECTRONIC_FACE_SHEET.getAlias(), corpid);
                        if (Objects.isNull(configEntity) || !Objects.equals(BasicConstant.ONE.toString(), configEntity.getConfigValue())){
                            continue;
                        }
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    workFlowPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            case RETURN:
                String returnStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ReturnEnum.ORDER_STATUS.getAttr(), ReturnStatusEnum.UNDER_REVIEW.getCode());
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if(Objects.equals(workFlowEnum,WorkFlowEnum.RETURN_INSTOCK) && !Objects.equals(returnStatus,ReturnStatusEnum.PROCESSING.getCode())){
                        continue;
                    }
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    workFlowPojo.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
            default:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    WorkFlowPojo workFlowPojo = new WorkFlowPojo();
                    BeanUtil.copyProperties(workFlowEnum, workFlowPojo);
                    changeValue(paasBusinessTypeToName, workFlowPojo);
                    workFlowPojoList.add(workFlowPojo);
                }
                break;
        }
    }

    /**
     * 改变名字
     * @param paasBusinessTypeToName
     * @param workFlowPojo
     */
    private void changeValue(Map<Integer, String> paasBusinessTypeToName, WorkFlowPojo workFlowPojo) {
        NameUtil.changeValue(paasBusinessTypeToName, workFlowPojo);
    }

    /**
     * 判断是否要换名字
     * @param paasBusinessTypeToName
     * @param pojoBusinessType
     * @return
     */
    private boolean needToChangeName(Map<Integer, String> paasBusinessTypeToName, Integer pojoBusinessType) {
        return NameUtil.needToChangeName(paasBusinessTypeToName, pojoBusinessType);
    }

    /**
     * 处理详情页头部按钮
     *
     * @param handelDetailPojo
     * @throws XbbException 异常
     */
    public void handelDetailButton(HandelDetailPojo handelDetailPojo) throws XbbException {
        Integer businessType = handelDetailPojo.getBusinessType();
        PaasFormDataEntityExt paasFormDataEntityExt = handelDetailPojo.getPaasFormDataEntityExt();
        List<ButtonPojo> buttonPojoList = handelDetailPojo.getButtonPojoList();
        UserVO userVO = handelDetailPojo.getLoginUser();
        Integer distributorMark = handelDetailPojo.getDistributorMark();
        List<BusinessDetailButtonEnum> buttonEnumList = BusinessDetailButtonEnum.getByBusinessTypeAndPermission(businessType, userVO.getPermSet());
        //在某些场景下需要移除业务中的详情页面的编辑按钮,团队成员需求增加的内容
        //removeEditButtom(buttonEnumList, userVO, paasFormDataEntityExt, businessType);
        JSONObject dataList = paasFormDataEntityExt.getData();
        String corpid = paasFormDataEntityExt.getCorpid();
        Long nowModelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch ( xbbRefTypeEnum) {
            case PAYMENT:
                String status = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getCode());
                Integer isRed = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList,PaymentEnum.RECEIVABLE_IS_RED.getAttr(),BasicConstant.ONE);
                boolean isRedReceivables = Objects.equals(status,PaymentStatusEnum.RED_RECEIVABLES.getCode()) && Objects.equals(isRed,BasicConstant.ONE);
                //红冲应收款按钮仅当未收金额大于0时展示
                double unAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(dataList, PaymentEnum.UN_AMOUNT.getAttr(), 0d);
                //未收、部分未收才有核销按钮：true非未收，false未收、部分未收
                boolean nonUnFlag = !PaymentStatusEnum.addPermission(status);
                Long modelType = paasFormDataEntityExt.getSysLong10();
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(PaymentStatusEnum.BAD_DEBT.getCode(), status) || Objects.equals(PaymentStatusEnum.PARTIAL_BAD_DEBT.getCode(), status)) {
                        // 坏账回款
                        if (!(Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_REVERT)
                                || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_PRINT))) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_REVERT)) {
                            continue;
                        }
                        if (nonUnFlag && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_WRITE_OFF)) {
                            //非未收、部分未收，则无核销应收按钮
                            continue;
                        }
                        // 正常回款
                        /*if (Objects.equals(PaymentStatusEnum.RECEIVABLES.getCode(), status) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_BAD)) {
                            continue;
                        }*/
                        //应收规则改造版本：（1）红冲应收款类型单据有无删除按钮：都可以删除  (2)普通类型应收款有无删除按钮：只有在手动创建模式下的手动创建类型的应收款才能删除
                        if(!isRedReceivables){
                            //不是红冲应收款
                            if(Objects.equals(buttonEnum,BusinessDetailButtonEnum.PAYMENT_DEL)){
                                if (!Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode())) {
                                    continue;
                                }
                                if (!Objects.equals(modelType, ModelTypeEnum.PLAN.getCode())) {
                                    continue;
                                }
                            }else if (unAmount <= 0 && Objects.equals(buttonEnum,BusinessDetailButtonEnum.PAYMENT_RED)) {
                                continue;
                            }
                        }else {
                            if(Objects.equals(buttonEnum,BusinessDetailButtonEnum.PAYMENT_RED)){
                                continue;
                            }
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojo.setDistributorMark(distributorMark);
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case PAY_PLAN:
                String payPlanStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PayPlanEnum.STATUS.getAttr(), PayPlanStatusEnum.UN_RECEIVABLES.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(PayPlanStatusEnum.BAD_DEBT.getCode(), payPlanStatus) || Objects.equals(PayPlanStatusEnum.PARTIAL_BAD_DEBT.getCode(), payPlanStatus)) {
                        // 坏账回款
                        if (!(Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_PLAN_DEL)
                                || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_PLAN_REVERT)
                                || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_PLAN_PRINT))) {
                            continue;
                        }
                    } else {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_PLAN_REVERT)) {
                            continue;
                        }
                        // 正常回款
                        if (Objects.equals(PayPlanStatusEnum.RECEIVABLES.getCode(), payPlanStatus) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_PLAN_BAD)) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case CUSTOMER_MANAGEMENT:
                Integer del = paasFormDataEntityExt.getDel();
                Integer isPublic = getIntegerOrDefaultFromFormData(dataList, CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                Integer isArchived = getIntegerOrDefaultFromFormData(dataList, CustomerManagementEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(del, DelEnum.DELETE.getDel())) {
                        // 客户回收站支持复制，其它的操作不支持
                        continue;
                    }
                    if (Objects.equals(isPublic, BasicConstant.ONE) && (Objects.equals(buttonEnum, BusinessDetailButtonEnum.CUSTOMER_CANCEL_ARCHIVED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CUSTOMER_ARCHIVED))) {
                        continue;
                    }
                    if (Objects.equals(isArchived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CUSTOMER_CANCEL_ARCHIVED)) {
                        continue;
                    } else if (Objects.equals(isArchived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CUSTOMER_ARCHIVED)) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case CLUE:
                Integer publicFlag = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                Integer archivedFlag = getIntegerOrDefaultFromFormData(dataList, ClueEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                String clueStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, ClueEnum.CLUE_STATUS.getAttr(), "");
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel())) {
                        // 线索回收站支持复制，其它的操作不支持
                        continue;
                    }
                    if (Objects.equals(publicFlag, BasicConstant.ONE) && (Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_CANCEL_ARCHIVED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_ARCHIVED)
                        || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_INVALID) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_FOLLOW))) {
                        continue;
                    }
                    if (Objects.equals(archivedFlag, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_CANCEL_ARCHIVED)) {
                        continue;
                    } else if (Objects.equals(archivedFlag, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_ARCHIVED)) {
                        continue;
                    }
                    if (Objects.equals(clueStatus, ClueStatusEnum.INVALID.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_INVALID)) {
                        continue;
                    }
                    if (Objects.equals(clueStatus, ClueStatusEnum.PENDING.getCode()) || Objects.equals(clueStatus, ClueStatusEnum.FOLLOWING_UP.getCode()) || Objects.equals(clueStatus, ClueStatusEnum.TRANSFORMED.getCode())) {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.CLUE_FOLLOW)) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case SALES_OPPORTUNITY:
                Integer archived = getIntegerOrDefaultFromFormData(dataList, SalesOpportunityEnum.IS_ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(archived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.OPPORTUNITY_CANCEL_ARCHIVED)) {
                        continue;
                    } else if (Objects.equals(archived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.OPPORTUNITY_ARCHIVED)) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case CONTRACT:
                Integer contractArchived = getIntegerOrDefaultFromFormData(dataList, ContractEnum.ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(contractArchived, ArchivedEnum.UN_ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CONTRACT_CANCEL_ARCHIVED)) {
                        continue;
                    } else if (Objects.equals(contractArchived, ArchivedEnum.ARCHIVED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.CONTRACT_ARCHIVED)) {
                        continue;
                    }
                   /* if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.CONTRACT_EDIT)) {
                        if (!saasDetailPermissionHelp.teamMembersCheckEditPermission(userVO, paasFormDataEntityExt, businessType)) {
                            continue;
                        }
                    }*/
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case ORDER:
                //订单状态
                Integer orderStatu = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, OrderEnum.STATUS.getAttr(), BasicConstant.ONE);
                //归档状态
                Integer archivedStatus = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, OrderEnum.ARCHIVED.getAttr(), ArchivedEnum.UN_ARCHIVED.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.ORDER_EDIT)) {
                        VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO(userVO, paasFormDataEntityExt);
                        boolean hasEditPermission = userTeamHelp.checkEditPermission(userVO, paasFormDataEntityExt, businessType) || sharePermissionHelp.verifySharePermission4EditWithRuleEngine(verifyUpdatePermissionDTO);
                        if (!hasEditPermission) {
                            continue;
                        }
                    }
                    if(Objects.equals(orderStatu, BasicConstant.ONE) || Objects.equals(orderStatu,BasicConstant.TWO)){
                        if (Objects.equals(orderStatu,BasicConstant.ONE) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_EDIT) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_DEL) &&!Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_PRINT)
                        && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_THROUGH) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_CANCELLATION)){
                            continue;
                        }else if (Objects.equals(orderStatu,BasicConstant.TWO) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_EDIT) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_DEL) &&!Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_PRINT)
                                    && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_CANCELLATION)){
                            continue;
                        }
                    }else {
                        if (!Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_EDIT) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_ARCHIVED) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_CANCEL_ARCHIVED) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_DEL) && !Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_PRINT)){
                            continue;
                        }else {
                            if (Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_ARCHIVED) && Objects.equals(archivedStatus,ArchivedEnum.ARCHIVED.getCode()) ){
                                continue;
                            }
                            if (Objects.equals(buttonEnum,BusinessDetailButtonEnum.ORDER_CANCEL_ARCHIVED) && Objects.equals(archivedStatus,ArchivedEnum.UN_ARCHIVED.getCode())){
                                continue;
                            }

                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(XbbRefTypeEnum.transferBusinessType2Index(buttonEnum.getLinkBusinessType()));
                    buttonPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case ORDER_OUTSTOCK:
                // 发货状态
                String expressStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, OrderOutStockEnum.EXPRESS_STATUS.getAttr(), OrderOutStockExpressStatusEnum.TO_BE_DELIVERED.getCode());
                // 是否电子面单发货
                Object taskId = dataList.get(OrderOutStockEnum.ELECTRONIC_TASK_ID.getAttr());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if(!Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.TO_BE_RECEIVED.getCode()) && ((Objects.equals(buttonEnum, BusinessDetailButtonEnum.ELECTRONIC_ORDER_PRINT) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.ELECTRONIC_ORDER_REPEAT_PRINT)))){
                        continue;
                    }
                    if (Objects.equals(expressStatus,OrderOutStockExpressStatusEnum.TO_BE_RECEIVED.getCode()) && ((Objects.equals(buttonEnum, BusinessDetailButtonEnum.ELECTRONIC_ORDER_PRINT) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.ELECTRONIC_ORDER_REPEAT_PRINT)))){
                        if (Objects.isNull(taskId)){
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(XbbRefTypeEnum.transferBusinessType2Index(buttonEnum.getLinkBusinessType()));
                    buttonPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case PRODUCTION_ORDER:
                Integer orderStatus = getIntegerOrDefaultFromFormData(dataList, ProductionOrderEnum.STATUS.getAttr(), 0);
                boolean isFinishOrClose = Objects.equals(orderStatus, ProductionOrderStatusEnum.FINISHED.getCode()) || Objects.equals(orderStatus, ProductionOrderStatusEnum.CLOSED.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(orderStatus, ProductionOrderStatusEnum.UNFINISHED.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PRODUCTION_ORDER_RESTART)) {
                        continue;
                    }
                    boolean isCloseOrFinish = Objects.equals(buttonEnum, BusinessDetailButtonEnum.PRODUCTION_ORDER_CLOSE) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PRODUCTION_ORDER_FINISH);
                    if (isFinishOrClose && isCloseOrFinish) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case INVOICE:
                Integer isCancel = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.IS_CANCEL.getAttr(), BasicConstant.ZERO);
                Integer isInvoiceRed = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.IS_RED.getAttr(), BasicConstant.ZERO);
                Integer hasRed = FastJsonHelper.getIntegerOrDefaultFromFormData(dataList, InvoiceEnum.HAS_RED.getAttr(), BasicConstant.ZERO);
                //关联客户
                String linkCustomer = dataList.getString(InvoiceEnum.CUSTOMER_NAME.getAttr());
                //关联合同
                String linkContract = dataList.getString(InvoiceEnum.CONTRACT_ID.getAttr());
                //获得在什么模式下创建的发票
                Long invoiceModelType = paasFormDataEntityExt.getSysLong10();
                boolean distributorMarkFlag = Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(isCancel, BasicConstant.ONE)) {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_CANCEL) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_RED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_EDIT)) {
                            continue;
                        }
                    } else if (Objects.equals(isInvoiceRed, BasicConstant.ONE)) {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_CANCEL) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_RED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_RETURN)) {
                            continue;
                        }
                    }else if(Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_EDIT)){
                        if(Objects.equals(hasRed,BasicConstant.ONE)){
                            continue;
                        }
                    } else {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_RETURN)) {
                            continue;
                        }
                        if (Objects.equals(hasRed, BasicConstant.ONE)) {
                            Double invoiceMoney = getDoubleOrDefaultFromFormData(dataList, InvoiceEnum.TOTAL_MONEY.getAttr(), BasicConstant.ZERO_DOUBLE);
                            double redTotalMoney = invoiceModel.getRedTotalMoney(paasFormDataEntityExt.getId(), paasFormDataEntityExt.getCorpid());
                            if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_CANCEL)) {
                                continue;
                            }
                            if (Arith.add(redTotalMoney, invoiceMoney) <= 0 && Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_RED)) {
                                continue;
                            }
                        }
                    }
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_DEL) && distributorMarkFlag) {
                        //经销商类型，去除发票删除按钮
                        continue;
                    }
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.INVOICE_LINK_CONTRACT)) {
                        //关联合同按钮判断
                        //.在①手动创建应收、③按出库产生应收模式下，允许对未关联过合同的发票进行关联，
                        //规则：a.发票已关联客户，但未关联任何合同 b.发票本身非红冲 c.非作废发票 d.未被红冲过          新添加关联合同按钮
                        boolean contractLinkButtonFlag = !Objects.equals(nowModelType, ModelTypeEnum.INVOICE.getCode()) && !Objects.equals(invoiceModelType, ModelTypeEnum.INVOICE.getCode()) && Objects.equals(isCancel, BasicConstant.ZERO)
                                && Objects.equals(isInvoiceRed, BasicConstant.ZERO) && Objects.equals(hasRed, BasicConstant.ZERO) && Objects.nonNull(linkCustomer) && StringUtil.isEmpty(linkContract);
                        if (!contractLinkButtonFlag) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojo.setDistributorMark(distributorMark);
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case PURCHASE_INVOICE:
                Integer purchaseInvoiceIsCancel = getIntegerOrDefaultFromFormData(dataList, PurchaseInvoiceEnum.IS_CANCEL.getAttr(), BasicConstant.ZERO);
                Integer purchaseInvoiceIsInvoiceRed = getIntegerOrDefaultFromFormData(dataList, PurchaseInvoiceEnum.IS_RED.getAttr(), BasicConstant.ZERO);
                Integer purchaseInvoiceHasRed = getIntegerOrDefaultFromFormData(dataList, PurchaseInvoiceEnum.HAS_RED.getAttr(), BasicConstant.ZERO);
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(purchaseInvoiceIsCancel, BasicConstant.ONE)) {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_CANCEL) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_RED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_EDIT)) {
                            continue;
                        }
                    } else if (Objects.equals(purchaseInvoiceIsInvoiceRed, BasicConstant.ONE)) {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_CANCEL) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_RED) || Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_RETURN)) {
                            continue;
                        }
                    }else if(Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_EDIT)){
                        if(Objects.equals(purchaseInvoiceHasRed,BasicConstant.ONE)){
                            continue;
                        }
                    } else {
                        if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_RETURN)) {
                            continue;
                        }
                        if (Objects.equals(purchaseInvoiceHasRed, BasicConstant.ONE)) {
                            Double invoiceMoney = getDoubleOrDefaultFromFormData(dataList, PurchaseInvoiceEnum.TOTAL_MONEY.getAttr(), BasicConstant.ZERO_DOUBLE);
                            double redTotalMoney = purchaseInvoiceModel.getRedTotalMoney(paasFormDataEntityExt.getId(), paasFormDataEntityExt.getCorpid());
                            if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_CANCEL)) {
                                continue;
                            }
                            if (Arith.add(redTotalMoney, invoiceMoney) <= 0 && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PURCHASE_INVOICE_RED)) {
                                continue;
                            }
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case COMMUNICATE_PLAN:
                String planStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, CommunicatePlanEnum.STATUS.getAttr(), "0");
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(planStatus, CommunicatePlanStatusEnum.CANCEL.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PLAN_QUIT)) {
                        continue;
                    } else if (Objects.equals(planStatus, CommunicatePlanStatusEnum.FINISH.getCode()) && Objects.equals(buttonEnum, BusinessDetailButtonEnum.PLAN_COMPLETE)) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case WORK_ORDER:
                UserEntity userEntity = new UserEntity();
                BeanUtil.copyProperties(userVO, userEntity);
                boolean isBoss = userVO.isAdminOrBoss();
                //工单完成状态可编辑权限
                Boolean isWorkOrderFinishedEdit = ProPermissionHelp.hasThisPermission(userVO,ProPermissionAliasEnum.WORK_ORDER_FINISHED_EDIT.getAlias());
                boolean isWorkOrderDispatcher = false;
                boolean isWorkOrderManager = false;
                boolean isCreator = Objects.equals(userEntity.getUserId(), paasFormDataEntityExt.getCreatorId());
                WorkOrderFlowUserEntity mainUser = workOrderFlowUserService.getMainUser(paasFormDataEntityExt.getId(), paasFormDataEntityExt.getCorpid());
                boolean isMain = false;
                if (Objects.nonNull(mainUser) && Objects.equals(mainUser.getUserId(), userVO.getUserId())) {
                    isMain = true;
                }

                Set<RoleSimpleVO> roleSet = userVO.getRoleSet();
                Set<String> permSet = userVO.getPermSet();

                for (RoleSimpleVO roleSimpleVO : roleSet) {
                    if (Objects.equals(roleSimpleVO.getId(), RoleEnum.WORKORDER_DISPATCHER.getCode())) {
                        isWorkOrderDispatcher = true;
                    }
                    if (Objects.equals(roleSimpleVO.getId(), RoleEnum.WORKORDER_MANAGER.getCode())) {
                        isWorkOrderManager = true;
                    }
                }
                Integer workOrderStatus = paasFormDataEntityExt.getStatus();
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.WORK_ORDER_CENETR_DETAIL_EDIT)) {
                        if (Objects.equals(workOrderStatus, WorkOrderStatusEnum.FINISH.getCode())) {
                            //工单"完成"状态，仅设置了工单完成状态可编辑权限情况下可编辑
                            if (!isWorkOrderFinishedEdit) {
                                continue;
                            }
                        } else {
                            //	创建人，老板、超管等最高权限人员，主负责人，派单员，工单主管。其他角色可自定义添加此权限。
                            if (!(isCreator || isBoss || isMain || ((isWorkOrderDispatcher || isWorkOrderManager) || permSet.contains(UpdateProPermissionAliasEnum.WORK_ORDER_UPDATE.getAlias())))) {
                                continue;
                            }
                        }
                    }
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.WORK_ORDER_CENETR_DETAIL_DEL)) {
                        if (!(isCreator || isBoss || isMain || (isWorkOrderManager && permSet.contains(DeleteProPermissionAliasEnum.WORK_ORDER_DEL.getAlias())) || permSet.contains(DeleteProPermissionAliasEnum.WORK_ORDER_DEL.getAlias()))) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case QUOTATION:
                Object isNew = dataList.get(QuotationEnum.IS_NEW.getAttr());
                if (isNew == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002);
                }
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.QUOTATION_EDIT)) {
                        if (Objects.equals(isNew, BasicConstant.ZERO)) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case PAYMENT_SHEET:
                //回款单类型
                String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.WRITE_OFF.getCode());
                //红冲、坏账、预收款：只有编辑、删除、打印
                boolean flag = PaymentSheetTypeEnum.isRed(paymentSheetType) || PaymentSheetTypeEnum.isBad(paymentSheetType) || Objects.equals(paymentSheetType, PaymentSheetTypeEnum.PREPAYMENT.getCode());
                boolean nonWriteOffFlag = !SheetTypeEnum.checkWriteOffPrepayment(paymentSheetType);
                Integer redBusinessType = PaymentSheetTypeEnum.getRedBusinessTypeByCode(paymentSheetType);
                Integer sheetBusinessType = PaymentSheetTypeEnum.getBusinessTypeByCode(paymentSheetType);
                //true 已红冲金额超过了回款单的回款金额/核销金额，无红冲按钮；false 未超过
                boolean redOver = true;
                if (!flag) {
                    redOver = checkRedOver(xbbRefTypeEnum, paasFormDataEntityExt.getId(), dataList, corpid, paymentSheetType);
                }
                distributorMarkFlag = Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode());
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_BAD)) {
                        //回款单详情无坏账按钮
                        continue;
                    } else if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_DEL) && distributorMarkFlag) {
                        //经销商类型，去除回款单删除按钮
                        continue;
                    }
                    if (flag) {
                        if (!(Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_EDIT)|| Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_DEL)|| Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_PRINT))) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_RED)) {
                        //回款单的红冲按钮的businessType要基于回款单类型来动态设置（比如不同类型回款单的详情，要置为不同的对应红冲类型）
                        if (redOver) {
                            continue;
                        }
                        buttonPojo.setLinkBusinessType(redBusinessType);
                    }  else if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAYMENT_SHEET_RED_BALANCE)) {
                        if (nonWriteOffFlag) {
                            continue;
                        }
                        //红冲预收款核销(退到余额)直接使用其linkBusinessType
                        if (redOver) {
                            continue;
                        }
                        buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    } else {
                        //回款单编辑、删除、打印按钮，要基于回款单类型得到businessType：因为回款单详情打开前端拿到的都是702，而要根据回款单data内的paymentSheetType确定具体是哪种类型回款单
                        buttonPojo.setLinkBusinessType(sheetBusinessType);
                    }
                    buttonPojo.setDistributorMark(distributorMark);
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case PAY_SHEET:
                //付款单类型
                String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaySheetTypeEnum.WRITE_OFF_PAY.getCode());
                //红冲、坏账、预付款：只有编辑、删除、打印
                flag = PaySheetTypeEnum.isRed(paySheetType) || PaySheetTypeEnum.isBad(paySheetType) || Objects.equals(paySheetType, PaySheetTypeEnum.PREPAY.getCode());
                redBusinessType = PaySheetTypeEnum.getRedBusinessTypeByCode(paySheetType);
                sheetBusinessType = PaySheetTypeEnum.getBusinessTypeByCode(paySheetType);
                //true 已红冲金额超过了付款单的付款金额/核销金额，无红冲按钮；false 未超过
                redOver = true;
                if (!flag) {
                    redOver = checkRedOver(xbbRefTypeEnum, paasFormDataEntityExt.getId(), dataList, corpid, paySheetType);
                }
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_SHEET_BAD)) {
                        //付款单详情无坏账按钮
                        continue;
                    }
                    if (flag) {
                        if (!(Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_SHEET_EDIT)|| Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_SHEET_DEL)|| Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_SHEET_PRINT))) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.PAY_SHEET_RED)) {
                        //付款单的红冲按钮的businessType要基于付款单类型来动态设置（比如不同类型付款单的详情，要置为不同的对应红冲类型）
                        if (redOver) {
                            continue;
                        }
                        buttonPojo.setLinkBusinessType(redBusinessType);
                    } else {
                        //付款单编辑、删除、打印按钮，要基于付款单类型得到businessType：因为付款单详情打开前端拿到的都是802，而要根据付款单data内的paySheetType确定具体是哪种类型付款单
                        buttonPojo.setLinkBusinessType(sheetBusinessType);
                    }
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case PAYMENT_TASK:
                String paymentTaskStatus = FastJsonHelper.getStringOrDefaultFromFormData(dataList, PaymentTaskEnum.STATUS.getAttr(), "0");
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(paymentTaskStatus, PaymentTaskStatusEnum.FINISH.getCode()) && buttonEnum.equals(BusinessDetailButtonEnum.PAYMENT_TASK_COMPLETE)) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojo.setDistributorMark(distributorMark);
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                // 未确认: 提醒确认  代客确认  重新生成
                // 已确认: 重新生成  归档
                // 待处理: 重新生成
                // 已归档: 取消归档
                buttonEnumList.clear();
                int statementArchive = dataList.getIntValue(CustomerStatementStatisticEnum.IS_ARCHIVED.getAttr());
                if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    String statementStatus = dataList.getString(CustomerStatementStatisticDistributorEnum.STATUS.getAttr());
                    if (Objects.equals(statementArchive, ArchivedEnum.UN_ARCHIVED.getCode())) {
                        if (Objects.equals(statementStatus, CustomerStatementStatusEnum.UNCONFIRMED.getCode())) {
                            buttonEnumList.add(BusinessDetailButtonEnum.REMIND_CONFIRM_STATEMENT);
                            buttonEnumList.add(BusinessDetailButtonEnum.VALET_CONFIRM_STATEMENT);
                        } else if (Objects.equals(statementStatus, CustomerStatementStatusEnum.CONFIRMED.getCode())) {
                            buttonEnumList.add(BusinessDetailButtonEnum.ARCHIVE_STATEMENT);
                        }
                        buttonEnumList.add(BusinessDetailButtonEnum.REGENERATE_STATEMENT);
                    } else if (Objects.equals(statementArchive, ArchivedEnum.ARCHIVED.getCode())) {
                        buttonEnumList.add(BusinessDetailButtonEnum.CANCEL_ARCHIVED_STATEMENT);
                    }
                } else {
                    if (Objects.equals(statementArchive, ArchivedEnum.UN_ARCHIVED.getCode())) {
                        buttonEnumList.add(BusinessDetailButtonEnum.ARCHIVE_STATEMENT);
                        buttonEnumList.add(BusinessDetailButtonEnum.REGENERATE_STATEMENT);
                    } else if (Objects.equals(statementArchive, ArchivedEnum.ARCHIVED.getCode())) {
                        buttonEnumList.add(BusinessDetailButtonEnum.CANCEL_ARCHIVED_STATEMENT);
                    }
                }
                buttonEnumList.add(BusinessDetailButtonEnum.CUSTOMER_STATEMENT_PRINT);
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    if (Objects.equals(BusinessDetailButtonEnum.CUSTOMER_STATEMENT_PRINT,buttonEnum)) {
                        // 对账单详情中打印需要获取生成对账单的打印模板，设计之初就是如此。。。
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode(), corpid, distributorMark, null);
                        ButtonExtraPojo buttonExtra = new ButtonExtraPojo();
                        buttonExtra.setBusinessType(XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode());
                        buttonExtra.setMenuId(paasFormEntityExt.getMenuId());
                        buttonExtra.setFormId(paasFormEntityExt.getId());
                        buttonExtra.setEntityId(dataList.getLongValue(CustomerStatementStatisticEnum.CUSTOMER_ID.getAttr()));
                        List<Long> checkingDate = new ArrayList<>();
                        JSONObject checkDate = dataList.getJSONObject(CustomerStatementStatisticEnum.CHECK_DATE.getAttr());
                        checkingDate.add(checkDate.getLongValue("startTime"));
                        checkingDate.add(checkDate.getLongValue("endTime"));
                        buttonExtra.setCheckingDate(checkingDate);
                        buttonPojo.setButtonExtra(buttonExtra);
                    }
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case DISTRIBUTOR_MANAGEMENT:
            case DISTRIBUTOR_CONTACT:
            case DISTRIBUTOR_ACCOUNT:
            case RETURN:
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(XbbRefTypeEnum.transferBusinessType2Index(buttonEnum.getLinkBusinessType()));
                    buttonPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case CREDIT_TEMPORARY_LIMIT:
                buttonEnumList.clear();
                String temporaryStatus = dataList.getString(CreditTemporaryLimitEnum.APPLY_STATUS.getAttr());
                int endTime = dataList.getIntValue(CreditTemporaryLimitEnum.END_TIME.getAttr());
                if (endTime >= DateTimeUtil.getTodayInt() && Objects.equals(temporaryStatus, CreditTemporaryApplyStatusEnum.NORMAL.getCode())) {
                    buttonEnumList.add(BusinessDetailButtonEnum.CREDIT_TEMPORARY_LIMIT_REVOKE);
                }
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(XbbRefTypeEnum.transferBusinessType2Index(buttonEnum.getLinkBusinessType()));
                    buttonPojo.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case OTHER_INCOME:
                //其他收入单类型
                String otherIncomeSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr(), OtherIncomeSheetTypeEnum.OTHER_INCOME.getCode());
                //红冲：只有编辑、打印
                boolean redFlag = OtherIncomeSheetTypeEnum.isRed(otherIncomeSheetType);
                redBusinessType = OtherIncomeSheetTypeEnum.getRedBusinessTypeByCode(otherIncomeSheetType);
                sheetBusinessType = OtherIncomeSheetTypeEnum.getBusinessTypeByCode(otherIncomeSheetType);
                //true 已红冲金额超过了其他收入单的金额，无红冲按钮；false 未超过
                redOver = true;
                if (!redFlag) {
                    redOver = checkRedOver(xbbRefTypeEnum, paasFormDataEntityExt.getId(), dataList, corpid, otherIncomeSheetType);
                }
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (redFlag) {
                        if (!(Objects.equals(buttonEnum, BusinessDetailButtonEnum.OTHER_INCOME_EDIT)|| Objects.equals(buttonEnum, BusinessDetailButtonEnum.OTHER_INCOME_PRINT))) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.OTHER_INCOME_RED)) {
                        //红冲按钮的businessType要基于其他收入单类型来动态设置（比如不同类型收入单的详情，要置为不同的对应红冲类型）
                        if (redOver) {
                            continue;
                        }
                        buttonPojo.setLinkBusinessType(redBusinessType);
                    } else {
                        //收入单编辑、打印按钮，要基于收入单类型得到businessType：因为收入单详情打开前端拿到的都是5710，而要根据收入单data内的sheetType确定具体是哪种类型回款单
                        buttonPojo.setLinkBusinessType(sheetBusinessType);
                    }
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case OTHER_EXPENSE:
                //其他支出单类型
                String otherExpenseSheetType = FastJsonHelper.getStringOrDefaultFromFormData(paasFormDataEntityExt.getData(), OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr(), OtherExpenseSheetTypeEnum.OTHER_EXPENSE.getCode());
                //红冲：只有编辑、打印
                redFlag = OtherExpenseSheetTypeEnum.isRed(otherExpenseSheetType);
                redBusinessType = OtherExpenseSheetTypeEnum.getRedBusinessTypeByCode(otherExpenseSheetType);
                sheetBusinessType = OtherExpenseSheetTypeEnum.getBusinessTypeByCode(otherExpenseSheetType);
                //true 已红冲金额超过了其他支出单的金额，无红冲按钮；false 未超过
                redOver = true;
                if (!redFlag) {
                    redOver = checkRedOver(xbbRefTypeEnum, paasFormDataEntityExt.getId(), dataList, corpid, otherExpenseSheetType);
                }
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (redFlag) {
                        if (!(Objects.equals(buttonEnum, BusinessDetailButtonEnum.OTHER_EXPENSE_EDIT)|| Objects.equals(buttonEnum, BusinessDetailButtonEnum.OTHER_EXPENSE_PRINT))) {
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    if (Objects.equals(buttonEnum, BusinessDetailButtonEnum.OTHER_EXPENSE_RED)) {
                        //红冲按钮的businessType要基于其他支出单类型来动态设置（比如不同类型支出单的详情，要置为不同的对应红冲类型）
                        if (redOver) {
                            continue;
                        }
                        buttonPojo.setLinkBusinessType(redBusinessType);
                    } else {
                        //支出单编辑、打印按钮，要基于支出单类型得到businessType：因为支出单详情打开前端拿到的都是5750，而要根据支出单data内的sheetType确定具体是哪种类型回款单
                        buttonPojo.setLinkBusinessType(sheetBusinessType);
                    }
                    buttonPojoList.add(buttonPojo);
                }
                break;
            default:
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    if (Objects.equals(buttonEnum.getAnEnum().getAttr(), SaasButtonEnum.CONTRACT_COMPARE.getAttr())){
                        Boolean compareButton = contractCompareUtil.showCompareButton(corpid, userVO.getPermSet(), userVO.getUserId());
                        if (!compareButton){
                            continue;
                        }
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojoList.add(buttonPojo);
                }
                break;
        }
    }

    /**
     * 需要根据当前人的可编辑权限去判断需不需要移除
     *
     * @param formDataDetailDTO
     * @param buttonPojoList
     * @param explainMap
     */
    public void removeEditButtom(FormDataDetailDTO formDataDetailDTO, List<ButtonPojo> buttonPojoList, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        Integer businessType = formDataDetailDTO.getBusinessType();
        UserVO loginUser = formDataDetailDTO.getLoginUser();
        //工单业务不处理
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            return;
        }
        if (CollectionsUtil.isNotEmpty(buttonPojoList)) {
            formDataDetailDTO.setDataCreatorId(paasFormDataEntityExt.getCreatorId());
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
            boolean perTag = commonPermissionHelp.checkEditPermissionWithoutShareEdit(formDataDetailDTO, verifyViewPermissionDTO, explainMap);
            if (!perTag) {
                Iterator<ButtonPojo> buttonPojoIterator =  buttonPojoList.iterator();
                while (buttonPojoIterator.hasNext()) {
                    ButtonPojo buttonPojo = buttonPojoIterator.next();
                    if (Objects.equals(SaasButtonEnum.EDIT.getAttr(), buttonPojo.getAttr())) {
                        buttonPojoIterator.remove();
                    }
                }
            }
        }
    }

    /**
     * 移动端业务需要根据当前人的可编辑权限去判断需不需要移除
     *
     * @param formDataGetDTO
     * @param topPermissionsPoJos
     * @param explainMap
     */
    public void mobileRemoveEditButtom(FormDataGetDTO formDataGetDTO, List<TopPermissionsPoJo> topPermissionsPoJos, Map<String, FieldAttrEntity> explainMap, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        Integer businessType = formDataGetDTO.getBusinessType();
        UserVO loginUser = formDataGetDTO.getLoginUser();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            return;
        }
        if (CollectionsUtil.isNotEmpty(topPermissionsPoJos)) {
            FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO();
            BeanUtil.copyProperties(formDataGetDTO, formDataDetailDTO);
            formDataDetailDTO.setDataCreatorId(paasFormDataEntityExt.getCreatorId());
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
            boolean perTag = commonPermissionHelp.checkEditPermissionWithoutShareEdit(formDataDetailDTO, verifyViewPermissionDTO, explainMap);
            if (!perTag) {
                Iterator<TopPermissionsPoJo> buttonPojoIterator =  topPermissionsPoJos.iterator();
                while (buttonPojoIterator.hasNext()) {
                    TopPermissionsPoJo buttonPojo = buttonPojoIterator.next();
                    if (Objects.equals(SaasButtonEnum.EDIT.getAttr(), buttonPojo.getAttr())) {
                        buttonPojoIterator.remove();
                    }
                }
            }
        }
    }

    /**
     * 处理评分,对于客户，线索这两种支持评分的业务，需要按照用户设置的评分规则来设置
     * @param businessType
     * @param paasFormDataEntityExt
     * @param dataDetailPojo
     * @throws XbbException
     */
    public void handelDetailScore(Integer businessType, PaasFormDataEntityExt paasFormDataEntityExt, DataDetailPojo dataDetailPojo) throws XbbException {
        if(Objects.nonNull(paasFormDataEntityExt) && XbbRefTypeEnum.checkScoreBusinessType(businessType)){
            String scoreShowValue = scoreRangeModel.getScoreShowValue(businessType, paasFormDataEntityExt);
            dataDetailPojo.setScore(scoreShowValue);
        }
    }


        /**
         * 判断回款单的红冲金额是否已经超过回款金额/核销金额
         *
         * @param xbbRefTypeEnum 业务类型
         * @param sheetId 数据id
         * @param dataList 数据data
         * @param corpid 公司id
         * @param sheetType 回款单类型
         * @return boolean true 已红冲金额超过了回款单的回款金额/核销金额，无红冲按钮；false 未超过
         * @throws XbbException
         * @author zcp
         * @date 19/12/8 008 16:56
         * @update 19/12/8 008 16:56
         * @since v1.0
         * @version v1.0
         */
    public boolean checkRedOver(XbbRefTypeEnum xbbRefTypeEnum, Long sheetId, JSONObject dataList, String corpid, String sheetType) throws XbbException {
        //已核销、预收款核销的红冲按钮，需要判断其红冲金额
        double redAmount;
        double amount;
        switch (xbbRefTypeEnum) {
            case PAY_SHEET:
                redAmount = saasPaySheetHelper.sumRedAmountBySheet(corpid, sheetId);
                amount = FundHelp.getSheetAmount4PaySheet(dataList, sheetType);
                break;
            case OTHER_INCOME:
                redAmount = saasOtherIncomeHelp.sumRedAmountBySheet(corpid, sheetId);
                amount = dataList.getDoubleValue(OtherIncomeEnum.AMOUNT.getAttr());
                break;
            case OTHER_EXPENSE:
                redAmount = saasOtherExpenseHelp.sumRedAmountBySheet(corpid, sheetId);
                amount = dataList.getDoubleValue(OtherExpenseEnum.AMOUNT.getAttr());
                break;
            default:
                redAmount = saasPaymentSheetHelper.sumRedAmountBySheet(corpid, sheetId);
                amount = FundHelp.getSheetAmount4PaymentSheet(dataList, sheetType);
                break;
        }
        //红冲金额为负，取正
        redAmount = Math.abs(redAmount);
        //已红冲的金额小于该回款单的回款金额/核销金额，才会有红冲按钮
        return redAmount >= amount;
    }

    public List<DetailTabPojo> handleDetailTabSort(String userId, String corpid, Long formId, Integer businessType, List<DetailTabPojo> tabPojoList) {
        return detailTabConfigService.handleDetailTabSort(userId, corpid, formId, businessType, tabPojoList);
    }

    /**
     * 特殊新建页
     *
     * @param explainList
     * @param businessType
     * @return
     */
    public void handelSaasSpecialItem(List<FieldAttrEntity> explainList, Integer businessType, Integer subBusinessType,
                                      Integer differenceBusinessType, Integer distributorMark) {
        if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT.getCode())
                && !Objects.equals(differenceBusinessType, XbbRefTypeEnum.RED_RECEIVABLES.getCode())) {
            //应收款新建移除客户合同关联新建回款
            explainList.removeIf(fieldAttrEntity -> !Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.CUSTOMER.getAttr())
                    && !Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.CONTRACT.getAttr())
                    && !Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.ADD_PAYMENT.getAttr()));
            explainList.forEach(fieldAttrEntity -> {
                if (Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.ADD_PAYMENT.getAttr())) {
                    fieldAttrEntity.setDistributorMark(distributorMark);
                }
            });
        }else if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT.getCode())) {
            explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.STATUS.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.GENERATION_DATE.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.RECEIVABLE_PERIOD.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.ESTIMATE_TIME.getAttr())
                    || Objects.equals(fieldAttrEntity.getAttr(), PaymentEnum.ADD_PAYMENT.getAttr()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PAY_PLAN.getCode())) {
            //付款计划新建移除供应商采购合同关联新建付款
            explainList.removeIf(fieldAttrEntity -> !Objects.equals(fieldAttrEntity.getAttr(), PayPlanEnum.LINK_SUPPLIER.getAttr())
                    && !Objects.equals(fieldAttrEntity.getAttr(), PayPlanEnum.LINK_PURCHASE.getAttr())
                    && !Objects.equals(fieldAttrEntity.getAttr(), PayPlanEnum.ADD_PAYPLAN.getAttr()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_CUSTOMER_COMMUNICATE.getCode())) {
            //客户详情新建跟进记录，非必填以及关联客户
            explainList.removeIf(fieldAttrEntity -> CustomerCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_CONTRACT_COMMUNICATE.getCode())) {
            //合同详情新建跟进记录，非必填、关联客户以及跟进业务
            explainList.removeIf(fieldAttrEntity -> CustomerCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_OPPORTUNITY_COMMUNICATE.getCode())) {
            //机会详情新建跟进记录，非必填以、关联客户以及跟进业务
            explainList.removeIf(fieldAttrEntity -> CustomerCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_CONTACT_COMMUNICATE.getCode())) {
            //联系人详情新建跟进记录，非必填以、关联客户以及联系人
            explainList.removeIf(fieldAttrEntity -> CustomerCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_SUPPLIER_COMMUNICATE.getCode())) {
            //供应商详情新建跟进记录，非必填、关联供应商
            explainList.removeIf(fieldAttrEntity -> SupplierCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_PURCHASE_COMMUNICATE.getCode())) {
            //供应商详情新建跟进记录，非必填、关联供应商以及联系人
            explainList.removeIf(fieldAttrEntity -> SupplierCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_QUOTATION_COMUNICATE.getCode())) {
            //报价单详情新建跟进记录，非必填、关联客户以及跟进业务
            explainList.removeIf(fieldAttrEntity -> CustomerCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && Objects.equals(subBusinessType, XbbRefTypeEnum.DETAIL_CLUE_COMUNICATE.getCode())) {
            //线索详情新建跟进记录，非必填、关联客户以及跟进业务
            explainList.removeIf(fieldAttrEntity -> CustomerCommunicateEnum.detailFilter(fieldAttrEntity.getAttr(), subBusinessType, fieldAttrEntity.getRequired(), fieldAttrEntity.getFieldType()));
        }
    }

    /**
     * 特殊编辑页
     *
     * @param explainList
     * @param businessType
     * @param formDataEntityExt
     */
    public void handelSaasSpecialUpdate(List<FieldAttrEntity> explainList, Integer businessType, PaasFormDataEntityExt formDataEntityExt, boolean formCopy, Integer distributorMark) throws XbbException {
        List<String> unableEditMemo= Arrays.asList(I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD, Locale.US), I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD, Locale.CHINA));
        //团队成员上线之后负责人唯一跟套餐相关了
        List<Integer> allBusinessList = FormOwnerUniqueEnum.getAllBusinessList();
        Integer feeType = commonHelp.getCurrentCompanyPackage(formDataEntityExt.getCorpid());
        boolean teamOwnerUniqueTag = !Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType()) && allBusinessList.contains(businessType)
                && Objects.equals(DistributorMarkEnum.OTHER.getCode(), distributorMark);
        // fix:18442 【移动端、web端】新建、编辑页面，不展示系统自动生成字段
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            if (unableEditMemo.contains(fieldAttrEntity.getUnableEditMemo())){
                fieldAttrEntity.setVisible(0);
            }
            if (Objects.equals(businessType, XbbRefTypeEnum.FUND_TRANSFER.getCode())) {
                List<String> unEditableAttrList = FundTransferEnum.getUnEditableAttrList();
                if (unEditableAttrList.contains(fieldAttrEntity.getAttr())) {
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
            }
            if (teamOwnerUniqueTag && Objects.equals(FieldTypeEnum.OWNERID.getAlias(), fieldAttrEntity.getAttr())) {
                fieldAttrEntity.setMultiple(FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType).getValue());
            }
        }

        if (Objects.equals(businessType, XbbRefTypeEnum.PAY_PLAN.getCode())) {
            explainList.removeIf(item -> Objects.equals(item.getSaasAttr(), PayPlanEnum.ADD_PAYPLAN.getSaasAttr()));
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) && !formCopy) {
            // 跟进记录编辑不需要下次跟进提醒相关的字段
            explainList.removeIf(item -> Objects.equals(item.getAttr(), CustomerCommunicateEnum.IF_REMIND.getAttr()) ||
                    Objects.equals(item.getAttr(), CustomerCommunicateEnum.NEXT_COMMUNICATE_TIME.getAttr()) ||
                    Objects.equals(item.getAttr(), CustomerCommunicateEnum.NOTIFY_TYPE.getAttr()) ||
                    Objects.equals(item.getAttr(), CustomerCommunicateEnum.NOTIFY_TIME.getAttr()) ||
                    Objects.equals(item.getAttr(), CustomerCommunicateEnum.NEXT_NOTIFY_MEMO.getAttr()) ||
                    Objects.equals(item.getAttr(), CustomerCommunicateEnum.ENTER_COMMUNICATE_PLAN.getAttr()) ||
                    Objects.equals(item.getAttr(), CustomerCommunicateEnum.FINISH_COMMUNICATE_PLAN_ID.getAttr())
            );
        }else if (Objects.equals(businessType,XbbRefTypeEnum.PRODUCT.getCode())){
            // 编辑产品时不显示库存数量字段
            explainList.removeIf(fieldAttrEntity -> Objects.equals(ProductEnum.STOCK.getSaasAttr(),fieldAttrEntity.getSaasAttr()));
            // 是否能更新成本 1-> 可以修改， 0 -> 不能修改
            int updateCost = 1;
            String corpid = formDataEntityExt.getCorpid();
            // 判断是否开启过进销存
            Boolean isJxcUse = false;
            // 是否关闭进销存
            int closeJxc = 1;
            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.JXC.getAlias(), corpid);
            if (Objects.nonNull(paasAppEntity)) {
                if (Objects.equals(paasAppEntity.getEnable(), 1)) {
                    isJxcUse = true;
                } else {
                    closeJxc = 0;
                }
            }
            // 父产品ID
            Long parentProductId = formDataEntityExt.getId();
            // 对开启开启过进销存的公司看产品有没有出入库
            if (isJxcUse) {
                // 找到对应的子产品信息
                List<PaasFormDataEntityExt> childProductList = this.findChildProductList(corpid, Collections.singletonList(parentProductId));
                if (CollectionsUtil.isEmpty(childProductList)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
                }
                // 根据子产品ID查询库存流水表是否存在数据，存在就说明改产品出入库过
                List<Long> childProductIdList = childProductList.stream().map(PaasFormDataEntityExt::getId).collect(Collectors.toList());
                Boolean existProduct = stockFlowBillModel.isExistProductIn(corpid, childProductIdList);
                // 如果存在流水记录，就不能跟新成本
                if (existProduct) {
                    updateCost = 0;
                }
            }
            JSONObject data = formDataEntityExt.getData();
            data.put(ProductConstant.UPDATE_COST, updateCost);
            data.put(ProductConstant.COLSE_JXC, closeJxc);

        }else if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(),businessType) && Objects.equals(distributorMark,DistributorMarkEnum.DISTRIBUTOR.getCode()) && Objects.nonNull(formDataEntityExt)){
            // 订货单审核通过的 产品 订单金额不允许编辑
            JSONObject orderData = formDataEntityExt.getData();
            if (Objects.nonNull(orderData)){
                String orderStatus = orderData.getString(OrderEnum.STATUS.getAttr());
                if (!Objects.equals(OrderStatusEnum.PENDING_ORDER_REVIEW.getCode(), orderStatus) && !Objects.equals(OrderStatusEnum.PENDING_FINANCIAL_REVIEW.getCode(), orderStatus)){
                    for (FieldAttrEntity fieldAttrEntity : explainList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(),OrderEnum.PRODUCT.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(),OrderEnum.AMOUNT.getAttr())){
                            fieldAttrEntity.setEditable(0);
                        }
                    }
                }
            }
        }else if (Objects.equals(XbbRefTypeEnum.REFUND.getCode(),businessType) && Objects.equals(distributorMark,DistributorMarkEnum.DISTRIBUTOR.getCode()) && Objects.nonNull(formDataEntityExt)){
            // 已完成的退货单不允许编辑
            JSONObject returnData = formDataEntityExt.getData();
            if (Objects.nonNull(returnData)){
                String returnOrderStatus = returnData.getString(ReturnEnum.ORDER_STATUS.getAttr());
                if(Objects.equals(ReturnStatusEnum.COMPLETED.getCode(),returnOrderStatus) || Objects.equals(ReturnStatusEnum.CLOSED.getCode(),returnOrderStatus)){
                    for (FieldAttrEntity fieldAttrEntity : explainList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(),ReturnEnum.PRODUCTS.getAttr())){
                            fieldAttrEntity.setEditable(0);
                            break;
                        }
                    }
                }
            }
        } else if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) && Objects.equals(distributorMark, DistributorMarkEnum.OTHER.getCode())) {
            // 开启联系人工作流的，客户的添加联系人字段不可编辑
            if (!formCopy && commonHelp.isOpenWorkFlow(formDataEntityExt.getCorpid())) {
                if (workflowModel.isSaasWorkFlowEnable(formDataEntityExt.getCorpid(), XbbRefTypeEnum.CONTACT.getCode())) {
                    for (FieldAttrEntity fieldAttrEntity : explainList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.ADD_CONTACT.getAttr())){
                            fieldAttrEntity.setEditable(BasicConstant.ZERO);
                            break;
                        }
                    }
                }
            }
        } else if (Objects.equals(XbbRefTypeEnum.SUPPLIER.getCode(), businessType) && Objects.equals(distributorMark, DistributorMarkEnum.OTHER.getCode())) {
            // 开启联系人工作流的，客户的添加联系人字段不可编辑
            if (commonHelp.isOpenWorkFlow(formDataEntityExt.getCorpid())) {
                if (workflowModel.isSaasWorkFlowEnable(formDataEntityExt.getCorpid(), XbbRefTypeEnum.SUPPLIER_CONTACT.getCode())) {
                    for (FieldAttrEntity fieldAttrEntity : explainList) {
                        if (Objects.equals(fieldAttrEntity.getAttr(), SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr())){
                            fieldAttrEntity.setEditable(BasicConstant.ZERO);
                            break;
                        }
                    }
                }
            }
        }
    }


    /**
     * 详情特殊返回解释
     *
     * @param explainList  解释
     * @param businessType 业务类型
     */
    public void handleDetailSpecialExplain(JSONObject data, List<FieldAttrEntity> explainList, Integer businessType, String platForm, String corpid, Long formId) throws XbbException {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        Integer linkedType;
        Integer linkedBusinessType;
        switch (redundantTemplateTypeEnum) {
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case REFUND_INSTOCK:
            case OTHER_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                linkedType = getIntegerOrDefaultFromFormData(data, InstockEnum.TYPE.getAttr(), 0);
                linkedBusinessType = InstockTypeEnum.getBusinessByCode(linkedType);
                explainList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), InstockEnum.REF_ID.getAttr())) {
                        item.setLinkedType(linkedBusinessType);
                    }
                });
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
                linkedType = getIntegerOrDefaultFromFormData(data, OutstockEnum.TYPE.getAttr(), 0);
                linkedBusinessType = OutstockTypeEnum.getBusinessByCode(linkedType);
                explainList.forEach(item -> {
                    if (Objects.equals(item.getAttr(), OutstockEnum.REF_ID.getAttr())) {
                        item.setLinkedType(linkedBusinessType);
                    }
                });
                break;
            case CUSTOMER:
                // 客户基本信息不展示关联信息
                explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.ASSOCIATED_INFO.getAttr()));
                Integer isPublic = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
                if (Objects.equals(isPublic, 1)) {
                    explainList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), CustomerManagementEnum.OWNER_ID.getAttr())) {
                            item.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                        }
                    });
                }
                break;
            case COMMUNICATE_PLAN:
                Iterator<FieldAttrEntity> iterator = explainList.iterator();
                while (iterator.hasNext()) {
                    FieldAttrEntity next = iterator.next();
                    if (Objects.equals(next.getAttr(), CommunicatePlanEnum.EXECUTOR.getAttr())) {
                        next.setFieldType(FieldTypeEnum.TEXT.getType());
                    } else if (Objects.equals(next.getAttr(), CommunicatePlanEnum.DELAY_CAUSE.getAttr())) {
                        iterator.remove();
                    } else if (Objects.equals(next.getAttr(), CommunicatePlanEnum.DELAY_MEMO.getAttr())) {
                        iterator.remove();
                    }
                }
                break;
            case SALES_OPPORTUNITY:
                break;
            case WORKREPORT:
                // 移动端工作报告详情基本信息不展示业绩数据
                explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), WorkReportFieldEnum.THIS_STATISTIC.getAttr()));
                break;
            case COMMUNICATE:
                Integer ifRemind = getIntegerOrDefaultFromFormData(data, CustomerCommunicateEnum.IF_REMIND.getAttr(), BasicConstant.ZERO);
                if (ifRemind == 1) {
                    if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), platForm)) {
                        // 移动端跟进记录详情基本信息不展示图片和录音
                        explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.VIDEO.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.IMAGES.getAttr()));
                    } else {
                        explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.IMAGES.getAttr()));
                    }
                } else {
                    if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), platForm)) {
                        // 移动端跟进记录详情基本信息不展示图片和录音
                        explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.VIDEO.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.IMAGES.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NEXT_COMMUNICATE_TIME.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NOTIFY_TYPE.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NOTIFY_TIME.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NEXT_NOTIFY_MEMO.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.ENTER_COMMUNICATE_PLAN.getAttr()));
                    } else {
                        explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.IMAGES.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NEXT_COMMUNICATE_TIME.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NOTIFY_TYPE.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NOTIFY_TIME.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.NEXT_NOTIFY_MEMO.getAttr()) ||
                                Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.ENTER_COMMUNICATE_PLAN.getAttr()));
                    }
                }
                break;
            case JXC_COMMUNICATE:
            case DISTRIBUTOR_COMMUNICATE:
                if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), platForm)) {
                    // 移动端跟进记录详情基本信息不展示图片和录音
                    explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.VIDEO.getAttr()) ||
                            Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.IMAGES.getAttr()));
                } else {
                    explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), CustomerCommunicateEnum.IMAGES.getAttr()));
                }
                break;
            case CONTRACT:
                Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                if (!isJxcUse) {
                    explainList.removeIf(fieldAttrEntity ->
                    Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.SHIP_STATUS.getAttr()));
                }
                break;
            case REFUND:
                isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                if (!isJxcUse) {
                    explainList.removeIf(fieldAttrEntity ->
                            Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.REFUND_STATUS.getAttr()));
                }
                break;
            case PAYMENT_TASK:
                Iterator<FieldAttrEntity> iteratorSen = explainList.iterator();
                while (iteratorSen.hasNext()) {
                    FieldAttrEntity next = iteratorSen.next();
                    if (Objects.equals(next.getAttr(), PaymentTaskEnum.EXECUTOR.getAttr())) {
                        next.setFieldType(FieldTypeEnum.TEXT.getType());
                    }
                }
                break;
            case CLUE:
                String status = FastJsonHelper.getStringOrDefaultFromFormData(data, ClueEnum.CLUE_STATUS.getAttr(), "");
                if (!Objects.equals(status, ClueStatusEnum.INVALID.getCode())) {
                    explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.INVALID_REASON.getAttr())
                            || Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.INVALID_MEMO.getAttr()));
                }
                Integer publicFlag = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_PUBLIC.getAttr(), 0);
                if (Objects.equals(publicFlag, 1)) {
                    explainList.forEach(item -> {
                        if (Objects.equals(item.getAttr(), ClueEnum.OWNER_ID.getAttr())) {
                            item.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    /**
     * 处理详情特殊返回的字段
     *
     * @param data         数据
     * @param dataId       数据id
     * @param businessType 业务类型
     * @param corpid       公司id
     * @throws XbbException 异常
     */
    public void handleDetailSpecialField(JSONObject data, Long dataId, Integer businessType, String corpid, Map<String, FieldAttrEntity> explainMap, Long formId, HandlerExplainDTO handlerExplainDTO) throws XbbException {
        if (Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())) {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put("planId", dataId);
            List<CommunicatePlanUserEntity> communicatePlanUserEntityList = communicatePlanUserModel.findEntitys(param);
            StringBuilder executorName = new StringBuilder();
            communicatePlanUserEntityList.forEach(communicatePlanUserEntity -> executorName.append(communicatePlanUserEntity.getUserName()).append(StringConstant.COMMA));
            if (!communicatePlanUserEntityList.isEmpty()) {
                executorName.deleteCharAt(executorName.length() - 1);
            }
            data.put(CommunicatePlanEnum.EXECUTOR.getAttr(), executorName.toString());
            Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, CommunicatePlanEnum.LINK_CUSTOMER.getAttr(), 0L);
            PaasFormDataEntityExt paasFormDataEntityExt = customerModel.getByKey(customerId, corpid);
            if (Objects.isNull(paasFormDataEntityExt)) {
                throw new XbbException(CommuicatePlanErrorCodeEnum.API_ERROR_214009);
            }
            JSONObject customerData = paasFormDataEntityExt.getData();
            String customerName = FastJsonHelper.getStringOrDefaultFromFormData(customerData, CustomerManagementEnum.NAME.getAttr(), "");
            JSONObject addressJsonObject = FastJsonHelper.getJsonObjectOrDefaultFromFormData(customerData, CustomerManagementEnum.ADDRESS.getAttr(), new JSONObject());
            String addressStr = addressJsonObject.getOrDefault(PaasConstant.PROVINCE, "").toString() + addressJsonObject.getOrDefault(PaasConstant.CITY, "").toString() + addressJsonObject.getOrDefault(PaasConstant.DISTRICT, "").toString() + addressJsonObject.getOrDefault(PaasConstant.ADDRESS, "").toString();
            // 查询关联客户的解释
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(paasFormDataEntityExt.getFormId(), corpid);
            Map<String, FieldAttrEntity> customerExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(Objects.nonNull(paasFormExplainEntity) && Objects.equals(paasFormExplainEntity.getDel(), DelEnum.NORMAL.getDel())) {
                String explains = paasFormExplainEntity.getExplains();
                if (Objects.nonNull(explains)) {
                    customerExplainMap = ExplainUtil.getExplainMap(explains, null);
                }
            }
            //协同团队
            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            userTeamService.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),false,mainUserMap,coUserMap);
            handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
            handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));

            List<DetaPhonePojo> detaPhonePojos = saasListHelp.cusCallPhone(customerData, RedundantTemplateTypeEnum.CUSTOMER.getCode(), corpid, customerExplainMap, handlerExplainDTO);
            JSONArray phoneArr = new JSONArray();
            packagePlanPhone(phoneArr, detaPhonePojos, customerName, addressStr);
            param.clear();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            List<PaasFormDataEntityExt> contactList = paasEsModel.selectByOneCondition(XbbRefTypeEnum.CONTACT.getCode(), ContactEnum.CUSTOMER_NAME.getAttr(), customerId, param, IndexTypeEnum.IDX_SAAS_CONTACT);

            List<Long> formIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            contactList.forEach(item -> formIds.add(item.getFormId()));
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("formIdIn", formIds);
            params.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            params.put(StringConstant.CORPID, corpid);
            List<PaasFormExplainEntity> explainList = paasFormExplainModel.findEntitys(params);
            Map<Long, Map<String, FieldAttrEntity>> formContactExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(PaasFormExplainEntity explain : explainList){
                Map<String, FieldAttrEntity> contactExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                if(Objects.nonNull(explain) && Objects.equals(explain.getDel(), DelEnum.NORMAL.getDel())) {
                    String explains = explain.getExplains();
                    if (Objects.nonNull(explains)) {
                        contactExplainMap = ExplainUtil.getExplainMap(explains, null);
                    }
                    formContactExplainMap.put(explain.getFormId(), contactExplainMap);
                }
            }

            for (PaasFormDataEntityExt contact : contactList) {
                JSONObject contactData = contact.getData();
                String contactName = FastJsonHelper.getStringOrDefaultFromFormData(contactData, ContactEnum.NAME.getAttr(), "");
                JSONObject contactAddressJsonObject = FastJsonHelper.getJsonObjectFromFormData(contactData, ContactEnum.ADDRESS.getAttr());
                String contactAddressStr;
                try {
                    contactAddressStr = contactAddressJsonObject.getString(PaasConstant.PROVINCE) + contactAddressJsonObject.getString(PaasConstant.CITY) + contactAddressJsonObject.getString(PaasConstant.DISTRICT) + contactAddressJsonObject.getString(PaasConstant.ADDRESS);
                } catch (Exception e) {
                    contactAddressStr = "";
                }
                Map<Long, List<String>> contactMainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, List<String>> contactCoUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                userTeamService.getUserIdMap(Collections.singletonList(contact.getDataId()),corpid,XbbRefTypeEnum.CONTACT.getCode(),false,contactMainUserMap,contactCoUserMap);
                handlerExplainDTO.setOwnerId(contactMainUserMap.get(contact.getDataId()));
                handlerExplainDTO.setCoUserId(contactCoUserMap.get(contact.getDataId()));

                List<DetaPhonePojo> contactDetaPhonePojos = saasListHelp.cusCallPhone(contactData, RedundantTemplateTypeEnum.CONTACT.getCode(), corpid, formContactExplainMap.get(contact.getFormId()), handlerExplainDTO);
                packagePlanPhone(phoneArr, contactDetaPhonePojos, contactName, contactAddressStr);
            }
            data.put(CommunicatePlanEnum.CONTACT_WAY.getAttr(), phoneArr);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode())) {
            Integer crmBusinessType = getIntegerOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
            if (!Objects.equals(crmBusinessType, BasicConstant.ZERO)) {
                String businessName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), "");
                if (!businessName.isEmpty()) {
                    businessName = RedundantTemplateTypeEnum.getByCode(crmBusinessType).getName() + PaasConstant.LEFT_BRACKET + businessName + PaasConstant.RIGHT_BRACKET;
                    data.put(CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), businessName);

                }
            }
        } else if (Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode())) {
            Integer jxcBusinessType = getIntegerOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_TYPE.getAttr(), BasicConstant.ZERO);
            if (!Objects.equals(jxcBusinessType, BasicConstant.ZERO)) {
                String businessName = FastJsonHelper.getStringOrDefaultFromFormData(data, CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), "");
                if (!businessName.isEmpty()) {
                    businessName = RedundantTemplateTypeEnum.getByCode(jxcBusinessType).getName() + PaasConstant.LEFT_BRACKET + businessName + PaasConstant.RIGHT_BRACKET;
                    data.put(CommunicateBaseEnum.COMMUNICATE_BUSINESS_HIDE.getAttr(), businessName);

                }
            }
        } else if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
            FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
            formConfigGetDTO.setCorpid(corpid);
            formConfigGetDTO.setBusinessType(businessType);
            formConfigGetDTO.setFormId(formId);
            Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
            String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig());
            Long customerLastTime = FastJsonHelper.getLongFromFormData(data, CustomerManagementEnum.LAST_CONNECT_TIME.getAttr());
            if(lastConnectTime != null) {
                String time = Objects.equals(lastConnectTime, "1") ? DateTimeUtil.getLastConnectTimeStr(customerLastTime) : DateUtil.getString(customerLastTime * 1000L, DateUtil.SDFYMDHM);
                data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), time);
            }

            String publicGroup = FastJsonHelper.getStringFromFormData(data, CustomerManagementEnum.PUBLIC_GROUP.getAttr());
            if(StringUtil.isNotEmpty(publicGroup)){
                PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorModel.getByKey(Long.valueOf(publicGroup), corpid);
                if (Objects.nonNull(publicGroupSeniorEntity)) {
                    data.put(CustomerManagementEnum.PUBLIC_GROUP.getAttr(), publicGroupSeniorEntity.getName());
                }
            }
        } else if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
            FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
            formConfigGetDTO.setCorpid(corpid);
            formConfigGetDTO.setBusinessType(businessType);
            formConfigGetDTO.setFormId(formId);
            Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
            String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig());
            Long lastTime = FastJsonHelper.getLongFromFormData(data, ClueEnum.LAST_CONNECT_TIME.getAttr());
            if(lastConnectTime != null){
                String time = Objects.equals(lastConnectTime, "1") ? DateTimeUtil.getLastConnectTimeStr(lastTime) : DateUtil.getString(lastTime * 1000L, DateUtil.SDFYMDHM);
                data.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), time);
            }

            String publicGroup = FastJsonHelper.getStringFromFormData(data, ClueEnum.PUBLIC_GROUP.getAttr());
            if(StringUtil.isNotEmpty(publicGroup)){
                PublicGroupSeniorEntity publicGroupSeniorEntity = publicGroupSeniorModel.getByKey(Long.valueOf(publicGroup), corpid);
                if (Objects.nonNull(publicGroupSeniorEntity)) {
                    data.put(ClueEnum.PUBLIC_GROUP.getAttr(), publicGroupSeniorEntity.getName());
                }
            }
        }else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_STATEMENT_STATISTIC.getCode())) {
            JSONObject checkDateObj = data.getJSONObject(CustomerStatementStatisticEnum.CHECK_DATE.getAttr());
            String startTime = DateTimeUtil.getString(checkDateObj.getLongValue("startTime") * 1000, DateTimeUtil.SDFDate);
            String endTime = DateTimeUtil.getString(checkDateObj.getLongValue("endTime") * 1000, DateTimeUtil.SDFDate);
            String checkDate = startTime + " 至 " + endTime;
            data.put(CustomerStatementStatisticEnum.CHECK_DATE.getAttr(), checkDate);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_LIMIT.getCode())) {
            // 计算单个经销商的临时额度、已用额度、可用额度
            creditLimitService.calculateCreditLimitSingle(corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), data);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode())) {
            // 过期状态判断
            String temporaryStatus = data.getString(CreditTemporaryLimitEnum.APPLY_STATUS.getAttr());
            int endTime = data.getIntValue(CreditTemporaryLimitEnum.END_TIME.getAttr());
            if (endTime < DateTimeUtil.getTodayInt() && !Objects.equals(temporaryStatus, CreditTemporaryApplyStatusEnum.REVOKED.getCode())) {
                data.put(CreditTemporaryLimitEnum.APPLY_STATUS.getAttr(), CreditTemporaryApplyStatusEnum.EXPIRED.getCode());
            }
        }else if (Objects.equals(businessType, XbbRefTypeEnum.ORDER_OUTSTOCK.getCode())){
            // 出库发货物流公司格式化
            String expressCode = data.getString(OrderOutStockEnum.EXPRESS_NAME.getAttr());
            String expressName = ExpressCodeEnum.getExpressNameByCode(expressCode);
            data.put(OrderOutStockEnum.EXPRESS_NAME.getAttr(), expressName);
        }
    }


    /**
     * 封装电话返回
     *
     * @param phoneArr       号码
     * @param detaPhonePojos pojo
     * @param name           名称
     * @param address        地址
     */
    private void packagePlanPhone(JSONArray phoneArr, List<DetaPhonePojo> detaPhonePojos, String name, String address) {
        for (DetaPhonePojo detaPhonePojo : detaPhonePojos) {
            JSONObject contactObj = new JSONObject();
            contactObj.put(StringConstant.PLAN_CONTACT_ATTR, name);
            String telNum = detaPhonePojo.getTelNum() == null ? "" : detaPhonePojo.getTelNum();
            contactObj.put(StringConstant.PLAN_PHONE_ATTR, detaPhonePojo.getName() + ": " + telNum);
            contactObj.put(StringConstant.PLAN_ADDRESS_ATTR, address);
            phoneArr.add(contactObj);
        }
    }

    /**
     * 处理客户详情页是否有栗子详情页图标
     * @param titlePojo
     * @param paasFormDataEntityExt
     * @return void
     * @author 石安
     * @date 2019-08-26
     */
    public void handelDetailClue(DetailTitlePojo titlePojo, PaasFormDataEntityExt paasFormDataEntityExt) {
        String pid = searchCustomerService.handelDetailClue(paasFormDataEntityExt);
        titlePojo.setPid(pid);
    }

    /**
     * 处理客户详情页是否有栗子详情页图标(移动端)
     * @param specialInfoPojo
     * @param paasFormDataEntityExt
     * @return void
     * @author 石安
     * @date 2019-08-29
     */
    public void handelDetailClue(MobileDetailSpecialInfoPojo specialInfoPojo, PaasFormDataEntityExt paasFormDataEntityExt) {
        String corpid = paasFormDataEntityExt.getCorpid();
        boolean flag = false;
        SearchCustomerCompanyEntity soukeEntity = searchCustomerCompanyModel.getByCorpid(corpid, SoukeMealEnum.SOUKE.getType());
        // 销客已不提供工商查询功能，这部分逻辑要去掉 2022-1-7 by hongxiao
//        SearchCustomerCompanyEntity businessEntity = searchCustomerCompanyModel.getByCorpid(corpid, SoukeMealEnum.BUSINESS.getType());
//        if (businessEntity != null && businessEntity.getExtraExpiry() > DateUtil.getInt()) {
//            flag = true;
//        }
        if (soukeEntity != null && soukeEntity.getExtraExpiry() > DateUtil.getInt()) {
            flag = true;
        }
        if (!flag) {
            return;
        }

        try {
            JSONObject jsonObject = searchCustomerService.haveEnterpriseInfo(paasFormDataEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()));
            if (jsonObject == null) {
                return;
            }else {
                Map<String, Object> operation = specialInfoPojo.getOperation();
                String pid = jsonObject.getString("PID");
                operation.put("pid", pid);
                specialInfoPojo.setOperation(operation);
            }
        } catch (XbbException e) {
            LOG.info("跳转栗子详情获取企业基本信息", e.getMsg());
        }
    }

    /**
     * 处理回款单详情页关联新建（目前回款单详情最多只有【新建发票】按钮）
     * @param paymentSheetType 回款单类型
     * @param dataList 数据data
     * @return boolean true 有新建发票按钮，false无新建发票按钮
     * @throws XbbException
     * @author zcp
     * @date 19/11/27 027 21:06
     * @update 19/11/27 027 21:06
     * @since v1.0
     * @version v1.0
     */
    public boolean checkWorkFlowAddInvoice4PaymentSheet(String paymentSheetType, JSONObject dataList) throws XbbException {
        //只有已核销、预收款才有新建发票按钮（预收款核销不能开票，因为预收款内可以开票，不能再重复开票）
        boolean flag = SheetTypeEnum.ifNewInvoice(paymentSheetType);
        if (flag) {
            Double invoiceAmount = getDoubleOrDefaultFromFormData(dataList, PaymentSheetEnum.INVOICE_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
            Double amount = getDoubleOrDefaultFromFormData(dataList, PaymentSheetEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
            //开票金额小于回款金额
            if (invoiceAmount < amount) {
                return true;
            }
        }
        return false;
    }
    /**
     * 处理付款单详情页关联新建（目前付款单详情最多只有【新建发票】按钮）
     * @param paySheetType 付款单类型
     * @param dataList 数据data
     * @return boolean true 有新建发票按钮，false无新建发票按钮
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public boolean checkWorkFlowAddInvoice4PaySheet(String paySheetType, JSONObject dataList) throws XbbException {
        //只有已核销、预付款才有新建发票按钮（预付款核销不能开票，因为预付款内可以开票，不能再重复开票）
        boolean flag = SheetTypeEnum.ifNewInvoice(paySheetType);
        if (flag) {
            Double invoiceAmount = getDoubleOrDefaultFromFormData(dataList, PaySheetEnum.INVOICE_AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
            Double amount = getDoubleOrDefaultFromFormData(dataList, PaySheetEnum.AMOUNT.getAttr(), BasicConstant.ZERO_DOUBLE);
            //开票金额小于回款金额
            if (invoiceAmount < amount) {
                return true;
            }
        }
        return false;
    }

    public void setTagInDetail(MobileFormCommonDetailVO mobileFormCommonDetailVO,Integer businessType,JSONObject data) throws XbbException{
        if(Objects.equals(businessType,XbbRefTypeEnum.PAYMENT.getCode())) {
            String status = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getAlias());
            if (Objects.equals(status, PaymentStatusEnum.UN_RECEIVABLES.getAlias()) || Objects.equals(status, PaymentStatusEnum.PARTIAL_RECEIPTS.getAlias())) {
                Long estimateTime = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentEnum.ESTIMATE_TIME.getAttr(), 0L);
                Double unAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PaymentEnum.UN_AMOUNT.getAttr(), 0D);
                if (Objects.nonNull(estimateTime) && estimateTime < DateUtil.getTodayInt() && unAmount > 0) {
                    JSONObject overdue = new JSONObject();
                    JSONObject detail = new JSONObject();
                    detail.put("memo", TagEnum.TAG_OVERDUE.getMemo());
                    overdue.put(TagEnum.TAG_OVERDUE.getAttr(), detail);
                    mobileFormCommonDetailVO.setTagData(overdue);
                }
            }
        }
    }

    /**
     * 塞入签署动态
     * @param formDataDetailDTO
     * @param paasFormDataEntityExt
     * @param labelsList
     * 创建时间 2020/6/24 2:27 PM
     * 修改时间 2020/6/24 2:27 PM
     * @author chy
     */
    public void addEsignTab4Paas(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, List<SummaryDataPoJo> labelsList) throws XbbException {
        UserVO userVO = formDataDetailDTO.getLoginUser();
        String corpid = paasFormDataEntityExt.getCorpid();
        Long formId = paasFormDataEntityExt.getFormId();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(formDataDetailDTO.getBusinessType());

        UserFormPermissionVO userFormPermissionVO = userService.getUserFormPermissionInternal(corpid,
                formDataDetailDTO.getUserId(), paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getMenuId());

        if (!esignHelp.hasEsignPermission(userFormPermissionVO,userVO.getPermSet(), xbbRefTypeEnum, corpid, formId)) {
            return;
        }

        Long id = paasFormDataEntityExt.getId();
        //获取签署状态
        EsignFlowStatusDTO esignFlowStatusDTO = new EsignFlowStatusDTO();
        BeanUtil.copyProperties(formDataDetailDTO, esignFlowStatusDTO);
        esignFlowStatusDTO.setCorpid(formDataDetailDTO.getCorpid());
        esignFlowStatusDTO.setFormId(formId);
        esignFlowStatusDTO.setDataId(id);
        EsignFlowStatusVO esignFlowStatusVO = esignService.getEsignFlowStatus(esignFlowStatusDTO);
        EsignFlowStatusEnum esignFlowStatusEnum = EsignFlowStatusEnum.getByCode(esignFlowStatusVO.getCode());
        Boolean effectiveFlowStatus = false;
        if (Objects.equals(esignFlowStatusEnum, EsignFlowStatusEnum.SIGNING) ||
                Objects.equals(esignFlowStatusEnum, EsignFlowStatusEnum.COMPLETE)) {
            effectiveFlowStatus = true;
        }
        /**
         * 流程状态(0-草稿,1-签署中,2-完成,3-撤销,4-终止（签署流程设置了文件有效截至日期，到期后触发),5-过期（签署截至日志到期后触发),7-拒签)
         */


        List<BusinessDetailTabEnum> tabEnumList = BusinessDetailTabEnum.getByBusinessType(XbbRefTypeEnum.ESIGN.getCode());
        SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
        for (BusinessDetailTabEnum tabEnum : tabEnumList) {
            BeanUtil.copyProperties(tabEnum.getAnEnum(), summaryDataPoJo);
            summaryDataPoJo.setAttr(tabEnum.getAnEnum().getKey());
        }
        if (effectiveFlowStatus) {
            labelsList.add(summaryDataPoJo);
        }
    }

    /**
     * 塞入签署动态
     * @param formDataDetailDTO
     * @param paasFormDataEntityExt
     * @param tabPojoList
     * 创建时间 2020/6/24 2:27 PM
     * 修改时间 2020/6/24 2:27 PM
     * @author chy
     */
    public void addEsignTab4Saas(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, List<DetailTabPojo> tabPojoList) throws XbbException {
       esignHelp.addEsignTab4Saas(formDataDetailDTO, paasFormDataEntityExt, tabPojoList);
    }

    public void addPaasEsignBtn(UserFormPermissionVO userFormPermissionVO, FormDataDetailDTO formDataDetailDTO,
                                 PaasFormDataEntityExt paasFormDataEntityExt, List<ButtonPojo> buttonPojoList){
        UserVO userVO = formDataDetailDTO.getLoginUser();
        String corpid = paasFormDataEntityExt.getCorpid();
        if (!esignHelp.hasEsignPermission(userFormPermissionVO, userVO.getPermSet(), XbbRefTypeEnum.PAAS,
                corpid, paasFormDataEntityExt.getFormId())){
            return ;
        }

        Long formId = paasFormDataEntityExt.getFormId();
        Long id = paasFormDataEntityExt.getId();
        EsignFlowStatusDTO esignFlowStatusDTO = new EsignFlowStatusDTO();
        BeanUtil.copyProperties(formDataDetailDTO, esignFlowStatusDTO);
        esignFlowStatusDTO.setCorpid(corpid);
        esignFlowStatusDTO.setFormId(formId);
        esignFlowStatusDTO.setDataId(id);
        EsignFlowStatusVO esignFlowStatusVO = null;
        try {
            esignFlowStatusVO = esignService.getEsignFlowStatus(esignFlowStatusDTO);
        } catch (XbbException e) {
            return ;
        }
        Integer code = esignFlowStatusVO.getCode();
        EsignFlowStatusEnum esignFlowStatusEnum = EsignFlowStatusEnum.getByCode(code);
        switch (esignFlowStatusEnum) {
            case COMPLETE:
                ButtonPojo esignButtonPojo = new ButtonPojo();
                BeanUtil.copyProperties(SaasButtonEnum.DOWNLOAD_CONTRACT, esignButtonPojo);
                buttonPojoList.add(esignButtonPojo);
                break;
            case SIGNING:
                //签订中无法发起签署、无法下载
                break;
            case UNSIGNED:
            case DRAFT:
            case UNDO:
            case TERMINATION:
            case EXPIRED:
            case REFUSAL:
                ButtonPojo downloadContractButtonPojo = new ButtonPojo();
                BeanUtil.copyProperties(SaasButtonEnum.ESIGN, downloadContractButtonPojo);
                buttonPojoList.add(downloadContractButtonPojo);
                break;
            default:
                break;
        }
    }

    /**
     * 根据父产品ID找到对应的子产品信息
     *
     * @param corpid          公司ID
     * @param parentProductId 父产品ID集合
     * @return 子产品信息集合
     * @throws XbbException xbb异常
     */
    private List<PaasFormDataEntityExt> findChildProductList(String corpid, List<Long> parentProductId) throws XbbException {
        ChildProductDTO childProductDTO = new ChildProductDTO();
        childProductDTO.setCorpid(corpid);
        childProductDTO.setParentProductId(parentProductId);
        PaasFormDataEsListVO childProductList = formDataEsService.getChildProductList(childProductDTO);
        if (Objects.isNull(childProductList) || CollectionsUtil.isEmpty(childProductList.getPaasFormDataESList())) {
            return new ArrayList<>();
        }
        return childProductList.getPaasFormDataESList();
    }

    /**
     * 团队成员需求，要求只有负责人、协同人字段同时存在并且启用的情况下才会显示团队tab栏
     *
     * @param tabPojoList 详情需要展示的一些tab栏列表
     * @param explainMap 表单解释
     */
    public void handleTeamTab(List<DetailTabPojo> tabPojoList,  Map<String, FieldAttrEntity> explainMap) {
        //因为现在只有负责人、协同人字段同时开启，这时候详情tab栏才显示负责团队tab,团队成员需求提出的
        if (CollectionsUtil.isNotEmpty(tabPojoList)) {
            Iterator<DetailTabPojo> detailTabPojoIterator = tabPojoList.iterator();
            while (detailTabPojoIterator.hasNext()) {
                DetailTabPojo detailTabPojo =  detailTabPojoIterator.next();
                if (Objects.equals(detailTabPojo.getKey(), DetailTabEnum.SALE_TEAM.getKey())) {
                    FieldAttrEntity ownerIdFieldAttr = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
                    FieldAttrEntity coUserIdFieldAttr = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
                    if (Objects.isNull(ownerIdFieldAttr) || Objects.isNull(coUserIdFieldAttr) || Objects.equals(ownerIdFieldAttr.getIsOpen(), BasicConstant.ZERO)
                            || Objects.equals(coUserIdFieldAttr.getIsOpen(), BasicConstant.ZERO)) {
                        detailTabPojoIterator.remove();
                    }
                }
            }
        }
    }
}
